Conditional Attributes in Sightly Templates (AEM/CQ)

aem, sightly, templating

Solution

When setting HTML attributes dynamically (with an expression), Sightly guesses your intention to simplify the writing:

If the value is an empty string or if it is the false boolean, then the attribute gets remove altogether. For instance `<p class="${''}">Hi</p>` and `<p class="${false}">Hi</p>` render just `<p>Hi</p>`.

If the value is the true boolean, then the attribute is written as a boolean HTML attribute (i.e. without attribute value, like for e.g. the checked, selected, or disabled form attributes). For instance `<input type="checkbox" checked="${true}">` renders `<input type="checkbox" checked>`.

You can then use two Sightly operators to achieve what you want (both work as in JavaScript): the ternary conditional operator, or the logical AND (`&&`) operator.

Ternary conditional operator

<ul data-sly-list="${items}" class="${condition1 ? 'selected' : ''}">
    <li class="${condition2 ? 'selected' : ''}">
        Lots of other markup here
    </li>
</ul>

Logical AND operator

For that, you additionally have to understand that like in JavaScript, `${value1 && value2}` returns `value1` if it is falsy (e.g. false, or an empty string), otherwise it returns `value2`:

<ul data-sly-list="${items}" class="${condition1 && 'selected'}">
    <li class="${condition2 && 'selected'}">
        Lots of other markup here
    </li>
</ul>

As said, in both examples the class attribute will be removed altogether if the corresponding condition is false.

Problem

In the Sightly templating language, for Adobe AEM6 (CQ), how do I add an attribute to an element only if a condition is true, without duplicating lots of code/logic? e.g. ``` <ul data-sly-list="${items}" ${if condition1} class="selected"${/if}> <li${if condition2} class="selected"${/if}> Lots of other code here </li> </ul> ```

Original source