Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 link_to with nested content_tag to create <a href with nested span - how to?

Hi I got 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-class to style in an image via css.

When I try the following implementations the result reflects just one part of the needed implementation:

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

results in:

<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") %>

results in:

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

Does anyone know how to accomplish?

like image 938
user1260945 Avatar asked Mar 10 '12 11:03

user1260945


2 Answers

Reading your question I did solve my problem. Than I propose another way to answer your question.

You could create a helper method to make this kind of link that you need. It would 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

The good about it is that your view 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 for sure, if other users want to, please do it.

like image 52
wviana Avatar answered Oct 02 '22 17:10

wviana


You could also nest tags by using alternative syntax for link_to helper

<%= link_to controller_path, :class=> "button-big layer" do %>
  Text
  <%= content_tag(:span, "", :class => "arrow_big" %>
<% end %>
like image 32
Johny Avatar answered Oct 02 '22 15:10

Johny