【问题标题】:rails 4 escaping garbled html in nested content tags,rails 4在嵌套内容标签中转义乱码html,
【发布时间】:2016-02-26 20:24:19
【问题描述】:

我有一个视图辅助方法,我想返回一个嵌套的 html 字符串。第一层和第二层返回格式正确的 html(这就是“转义的 html”的意思吗?)。然而,第三个是产生乱码(这是“未转义”吗?)。

"....content=\"test&lt;br/&gt;test&lt;br/&gt;test&lt;br/&gt;London&lt;br/&gt;test\"></meta></div></div>"

无论我走多远,如何确保嵌套内容正确显示?

我发现this 的答案非常有用,尽管这是在循环的上下文中,我在这里没有这样做。

这是我正在使用的方法,

  def opening_times_meta(venue)
    content_tag(:div, nil, class: 'facility-type', itemscope: true, itemtype: 'http://schema.org/Event') do
      content_tag(:meta, nil, content: venue.title, itemprop: 'name' )
      content_tag(:div, nil, class: 'hidden', itemprop: 'location', itemscope: true, itemtype: 'http://schema.org/Place') do
        content_tag(:meta, nil, itemprop: 'sameAs', content: request.original_url).html_safe
        content_tag(:meta, nil, itemprop: 'name', content: venue.title)
        content_tag(:meta, nil, itemprop: 'address', content: venue.address)
      end
    end
  end

【问题讨论】:

  • 尝试在 content_tag 的输出上调用 raw
  • 你能说清楚一点吗?

标签: html ruby-on-rails model-view-controller


【解决方案1】:

你可以试试这个代码:

def opening_times_meta(venue)
  content_tag(:div, nil, class: 'facility-type', itemscope: true, itemtype: 'http://schema.org/Event') do
    [
      content_tag(:meta, nil, content: venue.title, itemprop: 'name' ),
      content_tag(:div, nil, class: 'hidden', itemprop: 'location', itemscope: true, itemtype: 'http://schema.org/Place') do
        [
          content_tag(:meta, nil, itemprop: 'sameAs', content: request.original_url),
          content_tag(:meta, nil, itemprop: 'name', content: venue.title),
          content_tag(:meta, nil, itemprop: 'address', content: venue.address)
        ].join.html_safe
      end
    ].join.html_safe
  end
end  

但 IMO 更好的是把它移到视图中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多