开发者

add additional class to render partial

开发者 https://www.devze.com 2023-04-02 18:52 出处:网络
I\'m looking for some help regarding partials. I have created a partial for a menu on my site, but I would like to know whether I can add an additional class to a partial. More specifically, I am look

I'm looking for some help regarding partials. I have created a partial for a menu on my site, but I would like to know whether I can add an additional class to a partial. More specifically, I am looking to assign an additional class to an li menu object so that I can 开发者_JAVA百科indicate that the user is on that particular page.

Here is my code for the partial (I'm using HAML). It's named _menu.html.haml and it is located in the 'shared' folder.

.three.columns
  %ul#nav
    %li
      %a{:href => "../pages/about"} About
    %li
      %a{:href => "../pages/careers"} Careers
    %li
      %a{:href => "../pages/contact"} Contact Us
    %li

My code for the carrers.html.haml page is as follows:

 code...
 = render :partial => 'shared/menu'
 more code...

I would like to add a .active_page class to the careers link located in the partial. This class changes the background image behind the text to indicate that the user is on a specific page. More specifically, I'd like it to look like so:

%li.active_page
   %a{:href => "../pages/careers"} Careers

Is it possible to do this using partials?


The fact that you're using a partial doesn't change how you're able to use HAML, or ERB, or anything like that. If you want to add a class, yes, then just add .active_page on to an HTML tag. If it's a valid thing to do in HAML, then you can do it anywhere in a view, even if it happens to be a partial.

A partial is just modularized/reusable views. Just like you can use code inside an instance method and inside a class method, because they're just code, so can you use the same HAML code in a partial and in a "regular" view.


There are a bunch of ways to do this. I would not use partials, I would do:

%li{:class => @active_page=="careers" ? "active_page" : ""}
  %a{:href => "../pages/careers"} Careers

Assuming @active_page has been created by your controller.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号