简体   繁体   中英

Ruby on Rails: how do you add a class in a link_to helper?

how do you get a link_to to generate something like

<a class="myclass".....

this is my code

<%= link_to "link", :controller => :my_controller, :action => :index, :class=>("on" if request.path =~ /\/my_controller/ ) %>

If you read the API , you'll see the following example:

link_to(body, url_options = {}, html_options = {})

This means the syntax for link_to is "link to something, then something else in braces, then another thing in braces." Another way of interpreting it is that the chunks have to be hashes.

link_to "link",
        { :controller => :my_controller, :action => :index }, 
        { :class=>("on" if request.path =~ /\/my_controller/ ) }

Which can all be placed on one line if you like.

In your code, :class is being included in the url_options hash rather than html_options . Try something like this:

<%= link_to "link", {:controller => :my_controller, :action => :index}, {:class => ...} %>

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