passing value from HTL to JS | Community
Skip to main content
New Participant
January 31, 2022
Solved

passing value from HTL to JS

  • January 31, 2022
  • 2 replies
  • 3078 views

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

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by BrianKasingli

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

 

 

2 replies

JeevanRaj
New Participant
January 31, 2022

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

BrianKasingli
BrianKasingliAccepted solution
New Participant
January 31, 2022

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