Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

passing value from HTL to JS

Avatar

Level 5

for example in HTL i can access the element using  ${ } but how can access the same in js file 

i.e  html file-     ${geo.location}       -> this I can easily get location variable  in html file 

      the question is how can I achieve the ${geo.location} inside script tag in the same html itself

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

You can set an HTML data-attribute that can be accessed by Javascript.

 

Take a look at the code example below where we are utilizing the HTML data-attribute that will be accessed in the script block.

Sightly.html

<section data-sly-use.taxcal="com.sourcedcode.core.components.models.TaxCalculator"
  id="tax-calculator"
  data-year="${taxcal.year @ context='scriptString'}"></section>

<script>
const article = document.querySelector('#tax-calculator');
console.log(article.dataset.year);
</script>

sourced: https://sourcedcode.com/blog/aem/with-htl-pass-data-from-aem-backend-to-javascript

 

 

View solution in original post

2 Replies

Avatar

Correct answer by
Community Advisor

You can set an HTML data-attribute that can be accessed by Javascript.

 

Take a look at the code example below where we are utilizing the HTML data-attribute that will be accessed in the script block.

Sightly.html

<section data-sly-use.taxcal="com.sourcedcode.core.components.models.TaxCalculator"
  id="tax-calculator"
  data-year="${taxcal.year @ context='scriptString'}"></section>

<script>
const article = document.querySelector('#tax-calculator');
console.log(article.dataset.year);
</script>

sourced: https://sourcedcode.com/blog/aem/with-htl-pass-data-from-aem-backend-to-javascript

 

 

Avatar

Community Advisor

Hi @rahul234dabas 

There are couple of ways to do it. The easiest way is to set HTML data-attribute as suggestd by @BrianKasingli.

Another way is to use JavaScript Use api. Here is an article on JavaScript Use Api.

Thanks