How to add conditional logic in sightly code for an HTML attribute

Rahul picture Rahul · May 17, 2016 · Viewed 13.9k times · Source

I tried searching but somehow i cannot get my way around thinking what do i need to add dynamic tags inside html element using sightly code. Not sure if this is good practice or not, but wanted to ask. Now i know how to apply cssclass to class attribute in an href. But what if i want to inject the entire attribute "class='one'" in an href how do i do that?

Can this be done. I know I could do something like

<a href="${properties['jcr:titleurl']}" class="${properties.openinnewwindow ? 'nonunderline' : ''}"> <h3>${properties['jcr:title']}</h3></a>

but i want to do this,

<div class="col-md-12">       
<a href="${properties['jcr:titleurl']}"  data-sly-test="${properties.openinnewwindow ? 'class=one' : class='two'}"> <h3>${properties['jcr:title']}</h3></a>

Answer

nateyolles picture nateyolles · May 17, 2016

Use data-sly-test to determine whether to keep or remove the element, so it's not what you're looking for.

You mentioned that you don't want the class attribute if the variable is null or blank. Your provided code with the ternary operator will do just that.

<a href="#" class="${properties.openinnewwindow ? 'nonunderline' : ''}">link</a>

Sightly is very much like JavaScript in the concept of truthy/falsey. In your example if openinnewwindow is truthy (true, not null, or not undefined, etc...), the class attribute will be equal to nonunderline. If openinnewwindow is falsey, the class attribute will not appear in the rendered HTML.

Another way to write this code would be with the logical && operator. This syntax is what you're asking for:

<a href="#" class="${properties.openinnewwindow && 'nonunderline'}">link</a>

See the Sightly specification for more information.