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>
The expression language of Sightly has a few operators that allow to do things like that. In your case, you have two possibilities: the conditional operator, or the logical AND ( && ) operator. This operator works like data-sly-test , but at the level of the expression.
Description. data-sly-element attribute with example in AEM: data-sly-element is a sightly/htl attributes which replaces the element name of the host element. In this video I have created a template called newtemplate which points to demo component which is a page rendering component.
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.
<ul data-sly-list="${items}" class="${condition1 ? 'selected' : ''}">
<li class="${condition2 ? 'selected' : ''}">
Lots of other markup here
</li>
</ul>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With