简体   繁体   English

Rails:将空标记和内容添加到link_to

[英]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: 我正在尝试使用link_to帮助器生成一个链接,该链接将输出以下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. <i>标签不是HTML5中可自行关闭的标签。 Therefore the text after the i is treated as that element's content. 因此, i之后的文本被视为该元素的内容。

Have you tried using the block format of link_to? 您是否尝试过使用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. 这是我在我的应用程序中使用的图标标记助手,我经常将其作为link_to的第一个参数传递,它可以单独用于创建图标标记,也可以用于文本后面的图标标记。

  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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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