Search code examples
aemhtl

AEM 6.x: How to pass an HTL variable to clientlib/JS?


So I have the following lines which loads my javascript.

<sly data-sly-use.clientLib="${'/libs/granite/sightly/templates/clientlib.html'}" data-sly-unwrap />
<sly data-sly-call="${clientLib.js @ categories='myhost.mycustomJS'}" data-sly-unwrap />

I have an HTL property (example: ${properties.myCustomProperty}) that I want to pass to myCustomJS.

Any ideas how it can be done?

I've looked around the net but didn't find anything useful.

Thank you.


Solution

  • You are trying to access a server side property with client side script. As you may realize sightly executes at server end and rendered output is returned to browser. In your case you need to send the properties to browser to make it available for clientside scripts to consume.

    1. Technique 1: (Recommended) Data attributes - This is easiest to send since DOM structure doesnt change. Pass the values as data elements and retrieve using jquery. For example:

    var value = $('#mydiv').data('custom-property');
    console.log(value);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="mydiv" data-custom-property="${properties.myCustomProperty}" />

    1. Technique 2: (Old school) - Hidden variable - Add hidden variable into component rendering script; set the value of variable with HTL property and read the variable from clientside js using getElementById or jquery.
    2. Technique 3: (Not recommended) - Make a trip to server. If you dont want to dilute your DOM (maybe property is secret or not SEO friendly), you may need to make an ajax call to a sling servlet that returns the property value. There are multiple examples available for sling servlet you can refer to. ACS Sample, AEM 6.3 servlet, 1 more example. But do remember its not worth to make a trip to server just for 1 property.