Search code examples
aemsightlyhtl

How to check for undefined variable property in HTL (AEM)?


Newbie to AEM here. Say I have:

<div
     data-text="${myVariable.someProperty}"
     ...

I do not wish to have data-text to return a "undefined" string if it is undefined. I tried using the logical operator and it didn't work..

<div
     data-text="${myVariable.someProperty ? myVariable.someProperty : ''}"

I supposed that myVariable.someProperty returns undefined instead of a boolean value. Any ideas how I can check for undefined in HTL (or am I doing something completely wrong)?


Solution

  • HTL will not render anything for undefined values. Assuming an JS use-object:

    logic.js:

    use(function () {
        return {
            test: undefined
        };
    });
    

    and an HTL script:

    <div data-sly-use.logic="logic.js" data-text="${logic.test}"></div>
    

    the output will be:

    <div></div>
    

    The attribute is stripped as it is falsy (see attributes detailed examples). If you want to keep the attribute you might want to modify the HTL expression to ${logic.test || true}.

    If you modify your use-object to return an 'undefined' string:

    use(function () {
        return {
            test: 'undefined'
        };
    });
    

    then you get the following output:

    <div data-text="undefined"></div>
    

    In this case you might want to modify your expression to test for the 'undefined' string: ${logic.test == 'undefined' ? '': logic.test}. Again, you can keep the attribute by replacing '' with true.