【问题标题】:Embedded HTML in link_to body in Rails在 Rails 中的 link_to 正文中嵌入 HTML
【发布时间】:2011-03-15 20:56:41
【问题描述】:

在使用 link_to 方法生成的链接正文中嵌入 HTML 的最佳方法是什么?

我基本上想要以下内容:

<a href="##">This is a <strong>link</strong></a>

我一直在尝试按照Rails and the <span> tag 中的建议进行此操作,但没有运气。我的代码如下所示:

item_helper.rb

def picture_filter
    #...Some other code up here
    text = "Show items with " + content_tag(:strong, 'pictures')
    link_to text, {:pics => true}, :class => 'highlight'
end

item_view.html.erb

 #...
 <%=raw picture_filter %>
 #...

【问题讨论】:

    标签: ruby-on-rails link-to


    【解决方案1】:

    试试这个方法

    <%= link_to(raw("a <strong>strong</strong> link"),{:pics => true},{ :class => 'highlight'})  %>
    

    【讨论】:

    • 应用于我的示例,调用变为:link_to raw(text), {:pics => true}, :class=> 'highlight'
    【解决方案2】:
    = link_to "http://www.example.com" do
       <strong>strong</strong>
    

    【讨论】:

    • 好的,我刚刚:&lt;%= link_to destroy_user_session_path, method: :delete do %&gt;
    【解决方案3】:

    截至 2016 年,我更喜欢这种方法。

    <%= link_to my_path do %>
        This is a <strong>ape</strong>
    <% end %>
    

    【讨论】:

    • 我觉得应该&lt;%= link_to my_path do %&gt; This is a &lt;strong&gt;ape&lt;/strong&gt; &lt;% end %&gt;
    【解决方案4】:

    你可以使用html_safe

    <%= link_to ("<i class='someIcon'></i> Link").html_safe %>
    

    【讨论】:

      【解决方案5】:

      不确定这是否是最好的方法。

      但我已经非常成功地在 content_tag 调用中放置了很多视图助手。

      调用 .html_safe 也可能没有坏处

      link_to(content_tag(:span, "Show yada " + content_tag(:strong, "Pictures")), {:pics => true})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-20
        • 1970-01-01
        • 2021-11-01
        • 2023-04-04
        • 1970-01-01
        相关资源
        最近更新 更多