Search code examples
aemsightly

How to add data-attribute conditionally using HTL in AEM?


I've seen a ton of examples related to conditional attributes, they all talk about this:

<img  data-srcset="${myModel.isPrimaryImg ? '/img/image1.jpg': '/img/image2.jpg'}" >

This either renders

<img data-srcset="/img/image1.jpg" >

Or

<img data-srcset="/img/image2.jpg" >

Depeneding on whether ${myModel.isPrimaryImg} is true or false respectively

this is not what I want, the above example deals with the "value" part of the attribute

I want to put the ternery condition on the "Key" part of the attribute as below:

<img  ${myModel.isTrue ?'data-srcset=' : 'srcset='} = "/img/common-image.jpg" >

And I would expect it to render

Either

<img  data-srcset= "/img/common-image.jpg" >

Or

<img  srcset= "/img/common-image.jpg" >

This was possible using JSP as much as I remember

The only way I can expect it to work as I want is if I add the condition like this:

<img  data-sly-test="${myModel.isTrue}" data-srcset = "/img/common-image.jpg" ><!-- When TRUE -->
<img  data-sly-test="${!myModel.isTrue}" srcset = "/img/common-image.jpg" >!-- When FALSE -->

But this needs two whole tags to be present one for each condition

Is there a better way to put the ternary condition in HTL for data-attribute keys and not values ?

I have a lot of such tags so I was thinking if I could fit the condition in one line only or else I'll end up doubling the number of tags, where each tag will contain one attribute based on the value of the flag one for true and one for false condition.


Solution

  • You can either:

    1. Use data-sly-attribute and expose the attributes as a map via a Use-Object object. You can then control the map keys in your Use-Object.
    2. Take advantage of empty attributes not being rendered (spec) and do something like:
    <img data-srcset="${myModel.isTrue ? '/img/common-image.jpg' : ''}" srcset="${!myModel.isTrue ? '/img/common-image.jpg' : ''}">
    

    That is reasonably readable and will keep your HTL script HTML-valid.