【问题标题】:How to properly concatenate string and tag result?如何正确连接字符串和标记结果?
【发布时间】:2012-12-20 19:37:05
【问题描述】:

我正在制作一个用于创建带有文本和徽标图像的登录按钮的 rails 助手。 如果我仅将 text 或 image_tag 结果作为内容,则效果很好。

def test_helper
  anchor = content_tag :a, "enter by", :href => '#'
  concat content_tag :div, anchor, :class => 'login'
end

# result:
# <div class="login"><a href="#">enter by</a></div>

def test_helper
  anchor = content_tag :a, image_tag("logo.png"), :href => '#'
  concat content_tag :div, anchor, :class => 'login'
end

# result:
# <div class="login"><a href="#"><img src="assets/logo.png" /></a></div>

但是当我尝试传递连接结果时,它会在 html 源代码中返回一个带有转义符号的 img 标签:

def test_helper
  anchor = content_tag :a, "enter by" + image_tag("logo.png"), :href => '#'
  concat content_tag :div, anchor, :class => 'login'
end

<div class="login"><a href="#">enter by&lt;img src=&quot;/assets/logo.png&quot; /&gt;</a></div>

如何正确连接字符串和 content_tag 的结果?

【问题讨论】:

    标签: ruby-on-rails-3 helpers


    【解决方案1】:

    问题是因为在构建anchor_tag 时进行了连接。您需要在字符串文字上调用 html_safe 以避免转义:

    anchor = content_tag :a, "enter by".html_safe + image_tag("logo.png"), :href => '#'
    

    【讨论】:

    • 哦,对不起.. 复制粘贴时我失去了括号。
    • 使用 anchor.html_safe 我得到相同的结果((
    • 你是对的,这不是问题 - 更新了新的解决方案。
    • 它返回
      {:class=>"login"}
    • 好的,再试一次 :) 并使用括号以防 ruby​​ 在解析时感到困惑......
    猜你喜欢
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    相关资源
    最近更新 更多