简体   繁体   中英

Rails: Adding an empty tag plus content to link_to

I'm trying to generate a link using the link_to helper that will output the following HTML:

<a href="some_url"><i class="some_class"></i>Link Name</a>

However the code I'm using to try to accomplish this:

link_to(tag("i", class: options[:icon]) + title, url)

...is outputting:

<a href="some_url"><i class="some_class">Link Name</i></a>

Why is it doing this, and how can I fix it? Thanks.

EDIT:
I believe I found the issue.

<i> tags are not self-closable tags in HTML5. Therefore the text after the i is treated as that element's content.

Have you tried using the block format of link_to?

<%= link_to url do %>
  <%= tag("i", class: options[:icon]) %>
  Link Name
<% end %>

Tweak that to your needs and maybe you'll get what you're looking for.

This is the icon tag helper I use in my applications which I frequently pass as the first argument to link_to, which can either be used to create a icon tag alone, or an icon tag followed by text.

  def icon_tag(icon, *args)
    options = args.extract_options!
    text = args.first || options.delete(:text)
    if text.nil?
      content_tag :i, "", class: ["icon", "icon-#{icon}"] + options[:class].to_a
    else
      "#{icon_tag icon} #{text}".html_safe
    end
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM