在Rails中link_to主体中嵌入HTML

74

如何在使用link_to方法生成的链接中嵌入HTML内容是最佳实践?

我需要实现以下功能:

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

我一直在尝试按照Rails和<span>标签中建议的方法进行操作,但是没有成功。我的代码如下:

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 %>
 #...
5个回答

114

试试这种方式

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

应用于我的示例,调用变成了:link_to raw(text), {:pics => true}, :class => 'highlight' - Ryan

62
= link_to "http://www.example.com" do
   <strong>strong</strong>

2
好的,我刚刚写了这个代码:<%= link_to destroy_user_session_path, method: :delete do %> - Krzysztof Szewczyk

32

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

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

6
我认为应该是 <%= link_to my_path do %> 这是一只<strong>猿</strong> <% end %> - timlentse

17

您可以使用 html_safe

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

4

不确定这是否是最佳方式。

但我已经非常成功地将许多视图帮助程序放在content_tag调用中。

同时,调用.html_safe可能也有好处。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接