A simplified way to conditionally check if a class should be added to a HAML template

Possible duplicate:
Add class if condition is met in Haml (with Rails)

I use a template that allows me to mark a list item as current (using class=current ), highlighting it in the navigation bar.

In HAML, it looks like this:

 %li.current Menu item A %li Menu item B %li Menu item C 

I have this code in a Sinatra view and you want to programmatically add class=current depending on the parameter to the view.

How can I do this most neatly?

I am currently doing this:

  - if section == "pages" %li.current %a{:href => "#pages"} Pages - else %li %a{:href => "#pages"} Pages 

Which feels too verbose.

+5
source share
2 answers

You can include a condition to determine if a class is needed for% li

 %li{ :class => ('current' if section == "pages") } %a{ :href => "#pages" } Pages 
+17
source

If section may be a different line, rather than "pages" , you should use something like mguymon . But if it can only be nil , false or "pages" , this code is more concise:

 %li{ class:section && 'current' } %a{ :href => "#pages" } Pages 

This uses the principle that HAML skips the nil or false attributes, and each object in Ruby evaluates to true , with the exception of: false and nil .

So, if section is different from nil or false , then section && 'current' displays 'current' otherwise, it returns false , omitting the class attribute.

+3
source

Source: https://habr.com/ru/post/924906/


All Articles