Rails 3 link_to with nested content_tag to create <a href with nested range - how?

Hi, I have a noob question, I want to create the following HTML result:

<a href="/controller/action" class="button-big layer">TEXT<span class="arrow-big"></span></a> 

In the above HTML, I want to have text with a span-style class for an image in an image via css.

When I try to execute the following implementations, the result reflects only one part of the required implementation:

 <%= link_to "TEXT", controller_path, :class => "button-big layer" %> 

leads to:

 <a href="/controller/action" class="button-big layer">TEXT</a> 

and

 <%= link_to(content_tag(:span, "", :class => "arrow-big"), controller_path, :class => "button-big layer") %> 

leads to:

 <a href="/controller/action" class="button-big layer"><span class="arrow-big"></span></a> 

Does anyone know how to do this?

+8
href ruby-on-rails-3 link-to content-tag
source share
4 answers

You can also embed tags using alternative syntax for link_to helper

 <%= link_to controller_path, :class=> "button-big layer" do %> Text <%= content_tag(:span, "", :class => "arrow_big" %> <% end %> 
+28
source share

Just combine the text with the span:

 <%= link_to(("TEXT" + content_tag(:span, "", :class => "arrow-big")).html_safe, controller_path, :class => "button-big layer") %> 

You will need .html_safe around concatenation, as otherwise the + operator will avoid the HTML content content_tag.

+10
source share

Here you can use a different method without content_tag. Not the cleanest, but it works!

 <%= link_to '<span class="arrow_big"></span>'.html_safe, controller_path, class: "button-big layer" %> 
+2
source share

Reading my question, I solved the problem. Than I suggest another way to answer your question.

You can create a helper method to make the link you need. It will be something like this

 def link_with_text_and_span(href, text, span_options= {}, link_options = {}) span_tag = content_tag(:span, span_options[:content] || '', :class => span_options[:class] || '') link_to(span_tag, href, :class => link_options[:class] || '') end 

It’s good that your opinion will be cleaner. Then you can just call this helper method in your view

  <%= link_with_text_and_span("/controller/action", "TEXT", {class: 'arrow-big'}, class: button-big) %> 

PS: This code can be improved if other users want it, please do it.

+1
source share

All Articles