Embedded HTML in link_to body in Rails

Ruby on-RailsLink To

Ruby on-Rails Problem Overview


What is the best way to go about getting embedded HTML in the body of a link generated with the link_to method?

I basically want the following:

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

I have been trying to go about this as suggested in https://stackoverflow.com/questions/2685436/rails-and-the-span-tag but with no luck. My code looks like the following:

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 Solutions


Solution 1 - Ruby on-Rails

Try it this way

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

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

As of 2016 I prefer this method.

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

Solution 4 - Ruby on-Rails

you can use html_safe

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

Solution 5 - Ruby on-Rails

Not sure if this is the best way.

But I have been very successful in staking alot of the view helpers inside the content_tag call.

It also might not hurt to call a .html_safe

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyanView Question on Stackoverflow
Solution 1 - Ruby on-RailsValdisView Answer on Stackoverflow
Solution 2 - Ruby on-RailsmarkView Answer on Stackoverflow
Solution 3 - Ruby on-RailsGorillaApeView Answer on Stackoverflow
Solution 4 - Ruby on-RailsSyedView Answer on Stackoverflow
Solution 5 - Ruby on-RailsBurningponyView Answer on Stackoverflow