Search code examples
aemsightly

Add attribute in Sightly/HTL only if it exists (AEM)


I have a component that takes the path of an image from the dialog and renders it. Here's the snippet of the component -

<div class="${something}" style="background-image:url('${properties.backgroundImageReference @ context='styleString'}');">
</div>

This works fine but I would like to add a logic to generate the style attribute only if properties.backgroundImageReference exists.

Is there a quick way of doing this? Please note that I do not want to use an enclosing data-sly-test condition.

Thanks


Solution

  • You could have the whole style string generated in an Use-Object that could return null/empty when the property is not set, then the attribute will be skipped.

    See https://github.com/adobe/aem-core-wcm-components/blob/master/content/src/content/jcr_root/apps/core/wcm/components/container/v1/container/simple.html#L21 for an example!

    Another option would be to define the whole background style with data-sly-set and leverage the ternary operator:

    <div class="${something}" 
       data-sly-set.backgroundStyle="background-image:url('${properties.backgroundImageReference @ context='styleString'}');"
       style="${properties.backgroundImageReference ? backgroundStyle : ''}">
    </div>