ZK Zhao
ZK Zhao

Reputation: 21523

Rails: link_to does not generate 2 content_tag within

I want generate this in view

    <li>
      <%= link_to pop_path do  %>
        <span class="glyphicon glyphicon-signal"></span>
        Trending
      <% end %>
    </li>

So I made a helper

def nav_link2(link_text, link_path)
  content_tag(:li, class: 'active') do
    link_to link_path do
      content_tag(:span, nil, class: "glyphicon glyphicon-star")
      content_tag(:span, link_text)
    end
  end
end

However, it can only generate 1 span within, what's the problem?

Upvotes: 1

Views: 213

Answers (1)

zwippie
zwippie

Reputation: 15515

You have to concatenate the two content_tags in the link_to block, since only the last line from a block is returned and thus printed.

Join the two strings generated by content_tag and use html_safe so it gets rendered properly:

link_to link_path do
  content_tag(:span, nil, class: "glyphicon glyphicon-star") +
    content_tag(:span, link_text)
end.html_safe

Upvotes: 2

Related Questions