简体   繁体   中英

Rails+Slim: How to use link_to tag with controller & action name; and nested content in the anchor tag

This is what I have right now:

li
  = link_to {:controller => "controllername", :action => "actionname"}
    span.glyphicon.sidebar-icon.glyphicon-ok-circle
    span   WhoHas

However this won't work as link_to expects it's first argument to be the content inside the anchor tag. The contents I'd like inside the anchor tag are the following span blocks.

Any help would be much appreciated!

You said this:

However this won't work as link_to expects it's first argument to be the content inside the anchor tag.

This is not true. link_to can also accept a block instead, and it will use the content of the block instead:

link_to("/path/to/thing") do 
  "My link"
end

And, as such, does not require the first argument to be used as the text for the link. The documentation list the following signatures:

link_to(body, url, html_options = {})
  # url is a String; you can use URL helpers like
  # posts_path

link_to(body, url_options = {}, html_options = {})
  # url_options, except :method, is passed to url_for

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

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

The last two options are what you're looking for.

However, the real reason your code doesn't work is because you're using braces without parentheses - basically, method { :hello => "world" } doesn't do what you think it does. the method { } syntax is reserved for blocks, so it's expecting the contents of a block - which it doesn't find. Rather, it finds a key-value association, which is reserved for hashes. Essentially, Ruby tries to interpret it as a block, but fails. So your options are to either encapsulate it with parentheses, like so: method({ :hello => "world" }) , or drop the braces, like so: method :hello => "world" . You'll also need to add a do at the end of your link_to to have the content be a block, so your code looks like this now:

li
  = link_to :controller => "controllername", :action => "actionname" do
    span.glyphicon.sidebar-icon.glyphicon-ok-circle
    span   WhoHas

Hope that helps.

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