在 Rails 7.0 及更早版本中,我们自定义了 Trix 编辑器以嵌入 YouTube 视频。按照惯例,视频将通过 iframe 标签嵌入。 Rails 清理程序会删除此标签,因为它可能会被滥用来嵌入恶意网站。
允许 config/initializers/action_text.rb 中的标记用于实现此目的。
Rails.application.config.after_initialize do
ActionText::ContentHelper.allowed_tags << "iframe"
end
Rails 7.1 有一个新的 HTML5 清理器,但旧的 HTML4 清理器仍然可以使用。这意味着应用程序启动时 ActionText::ContentHelper
尚未定义,因此上面的代码片段将使服务器崩溃。我预计 after_initialize
会等待足够长的时间来加载 sanitizer ,但没有骰子。
Unable to load application: NoMethodError: undefined method `<<' for nil:NilClass
config/initializers/action_text.rb:2:in `block in <top (required)>': undefined method `<<' for nil:NilClass (NoMethodError)
关于如何在 Rails 7.1 中允许清理标签有什么想法吗?
最佳答案
我也遇到了同样的问题。根据 ActionView 7.1.0 CHANGELOG,在应用程序中设置之前它为零。
The Rails 7.1 configuration will set this to Rails::HTML5::Sanitizer when it is supported, and fall back to Rails::HTML4::Sanitizer. Previous configurations default to Rails::HTML4::Sanitizer.
As a result of this change, the defaults for ActionText::ContentHelper.allowed_tags and .allowed_attributes are applied at runtime, so the value of these attributes is now 'nil' unless set by the application. You may call sanitizer_allowed_tags or sanitizer_allowed_attributes to inspect the tags and attributes being allowed by the sanitizer.
因此,我决定将所有标签从“rails-html-sanitizer”gem 复制到 config/initializers/action_text.rb 并在那里添加我的特定标签
Rails.application.config.after_initialize do
ActionText::ContentHelper.allowed_tags = Set.new([
"a",
"abbr",
"acronym",
"address",
... # more tags go here
]).freeze
end
它完成了任务。
关于ruby-on-rails - 允许在 Rails 7.1 中使用带有新清理程序的 ActionText 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77366033/