Search code examples
csshamlc

Conditional CSS Class In Haml Coffee Template


Give the following code in a .hamlc template:

.myDiv
  some content here

What if I wanted to add the class "special" to the div.myDiv based on a property of the model passed to the template.

so if is_special property of the model was true, the output would be what is shown below:

<div class="myDiv special">
   some content here
</div>

and if is_special was false, the output would be:

<div class="myDiv">
  some content here
</div>

Solution

  • You can add a class attribute:

    .myDiv{ class: 'hoho' }
      some content here
    

    which will result in:

    <div class='hoho myDiv'>
      some content here
    </div>
    

    Now you can add some CoffeeScript code to the attribute to make it dynamic:

    .myDiv{ class: @model.get('status') }
      some content here