custom JS that's being inserted via clientlibs - how do I pass a vale to the JS? | Community
Skip to main content
jayv25585659
Level 8
July 10, 2023
Solved

custom JS that's being inserted via clientlibs - how do I pass a vale to the JS?

  • July 10, 2023
  • 3 replies
  • 968 views

as above. As an example, I want to pass a property (example: ${properties.myVar}) to the javascript.

 

How can I do it? Thank you.

 

<sly data-sly-use.clientlib="/libs/granite/sightly/templates/clientlib.html" data-sly-call="${clientlib.js @ categories='acme.my-custom-clientlibs-here'}"/>

 

In my javascript, I do something like this

 

alert("myVar: " + myVar);
Best answer by milind_bachani

Hi @jayv25585659 ,

 

You can define the variable in your html using <script> tag :

<script> var myVar= "${properties.myProp @ context='scriptString'}"; </script>

And the same can be accessed in JS directly using myVar.

 

Best,

Milind

3 replies

Rohit_Utreja
Community Advisor
Community Advisor
July 10, 2023

You can populate this value in the HTML and later grab this value in JS while rendering the page.

milind_bachani
Adobe Employee
milind_bachaniAdobe EmployeeAccepted solution
Adobe Employee
July 10, 2023

Hi @jayv25585659 ,

 

You can define the variable in your html using <script> tag :

<script> var myVar= "${properties.myProp @ context='scriptString'}"; </script>

And the same can be accessed in JS directly using myVar.

 

Best,

Milind

ayush-anand
Level 4
July 10, 2023

@jayv25585659 You can specify this "myVar" value in a data-attribute of any tag and then can fetch this value in JS. Below code snippet my help: 

<div data-customValue="${myVar}" id="val"></div>

<script>
const elm= document.querySelector('#val');
alert("myVar: " + elm.dataset.customValue);
</script>

 Regards,

Ayush