Rails 如何在 link_to 内加一个其他 html 标签

stephen · February 09, 2012 · Last by HyeKyoZ replied at January 21, 2017 · 8344 hits

在网上找到了在 link_to 这个 help 添加一个 image_tag 的方法 那添加其他标签呢? 类如一个 i!

<%= link_to content_tag(:i, "ha"), "http://google.com" %>

怎么多了个分号...

像这样? <%= link_to raw("<strong>Edit</strong>"), edit_resource_url(r) %>

@cqpx 行么?<%= link_to "个人资料", settings_index_path, :class=>'list_link' %> 按照你的加上去,报错的!

#4 楼 @stephen 别加那个分号,ruby-china 的 bug,给我加了一个分号

@cqpx 没加分号呢···是这样么?

<%= link_to content_tag(:i, :class=>'aa'),  "个人资料", settings_index_path, :class=>'list_link' %>

@Rei 报错

undefined method `stringify_keys` for

你把参数打错了 content_tag(:i, "", :class=>'aa')

#7 楼 @stephen

参考一下这两个 helper 的参数 http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag

你的代码"个人资料"在第二个参数,应该是 url 的位置。

<%= link_to content_tag(:li,  "个人资料", :class=>'aa'), settings_index_path, :class=>'list_link' %>

@cqpx 改了但报同一个错!

插个别的问题,a 嵌套 li 标签应该会产生问题,li 需要是 ul/ol 的直接子节点。

两个方法...一个是 content_tag 或者你 raw("

  • ") 我喜欢前者。

    BTW: 你这是什么 settings_index_path

  • 另外 link_to 可以用 block 的:

    <%= link_to(@profile) do %>
      <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
    <% end %>
    

    #13 楼 @niedhui 谢谢,又学了一手

    @Rei @poshboytl 误会了,我不是插 li,我是插 i。 @niedhui 用过,如何改成我的代码呢,我替换成这样,报错

    <%= link_to "个人资料", settings_index_path, :class=>'list_link'  do %>
      <i></i>
    <% end %>
    

    #15 楼 @stephen 哈哈,我把 ! 看进去了。

    link_to(url, html_options = {}) do
      # name
    end
    

    name 部分写 i 标签

    原来还可以用 block 阿,还是第一次知道

    我正好遇到这个问题,一开始看了代码里的注释没搞懂,最后看了楼上发的文档才弄懂。

    代码的注释是这样的:

    # You can use a block as well if your link target is hard to fit into the name parameter. ERB example:
         #
         #   <%= link_to(@profile) do %>
         #     <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
         #   <% end %>
         #   # => <a href="/profiles/1">
         #          <strong>David</strong> -- <span>Check it out!</span>
         #        </a>
    

    这个链接里的文档 我根据文档里的这个

    link_to(url, html_options = {}) do
      # name
    end
    

    举个例子:

    <%= link_to logout_path, method: :delete, class: 'dropdown-item' do %>
      <i class="fa fa-sign-out" aria-hidden="true"></i>
      Log out
    <% end %>
    

    最后生成

    <a class="dropdown-item" rel="nofollow" data-method="delete" href="/logout">
      <i class="fa fa-sign-out" aria-hidden="true"></i>
      Log out
    </a>
    
    You need to Sign in before reply, if you don't have an account, please Sign up first.