Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Attributes in Sightly Templates (AEM/CQ)

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>
like image 943
Alasdair McLeay Avatar asked Jul 03 '14 09:07

Alasdair McLeay


People also ask

How do you write or condition in sightly?

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.

What is data sly attribute?

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.


1 Answers

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.

like image 80
Gabriel Walt Avatar answered Sep 18 '22 12:09

Gabriel Walt