ruby-on-rails - 如何转义 yield 返回的值

标签 ruby-on-rails escaping yield html

我最近在转义模板中 yield 返回的值时遇到了问题。

在我的布局中,我生成了元描述,以便我可以从我的模板中定义它

<meta name="description" content="<%= yield :html_description %>" />

这是我的模板,不幸的是,它没有按预期转义值:

<% content_for :html_description, 'hello "you" guy' %>
<meta name="description" content="hello "you" guy" />

我试图用 h() 转义器转义它,但它不起作用:

<meta name="description" content="<%= h(yield :html_description) %>" />
<meta name="description" content="hello "you" guy" />

我也尝试过使用 escape_once(),但它做的太多了:

<meta name="description" content="<%= escape_once(yield :html_description) %>" />
<meta name="description" content="hello &amp;quot;you&amp;quot; guy" />

但是,通过将返回值与字符串连接起来,它解决了问题:

<meta name="description" content="<%= '' + (yield :html_description) %>" />
<meta name="description" content="hello &quot;you&quot; guy" />

有人理解这种行为吗?

你有比这个巧合修复的串联更好的解决方案吗?

我正在使用 Rails 2.3.8 - 谢谢!

最佳答案

对于meta、img、br等自闭标签,可以使用“tag”方式。

<%= tag(:meta, :name => 'description', :content => yield(:html_description)) %>

这给了你

<meta content="&quot;I am surrounded by quotes&quot;" name="description" />

关于ruby-on-rails - 如何转义 yield 返回的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4104313/

相关文章:

ruby-on-rails - 仅响应 rails 中的 json

ruby-on-rails - 命名空间 JSONAPI 资源和 Controller

ruby-on-rails - 将持续时间转换为小时 :minutes:seconds (or similar) in Rails 3 or Ruby

python - 将带有 yield(string) 的 python 函数翻译成 C++

ruby-on-rails - 如何在 Rails 模型中渲染_to_string?

python - 将未转义的空白打印到 shell

Java -> Apache Commons StringEscapeUtils -> escapeJavaScript

javascript - 在 JavaScript 中取消转义撇号 (')?

scala - 使用 Scala 延续实现 yield ( yield 返回)

c# - 重载使用 yield return