Pass value from JS to sly attribute

viki1101

20-08-2020

Hello Community - We are using HTL Use-API to get the cookie value from the script and printing the value in the component. For some reason, it is not working as expected and it retains the previous selected value. AEM document says "Use-API" could be slower.

 

Is there any way to use the return value from a java-script to the data-sly-test attribute?

 

<sly data-sly-use.productValue="test.js" data-sly-test="${productValue.resultsFound}">
<div>${productValue.results}</span></div>
</sly>

Accepted Solutions (1)

Accepted Solutions (1)

Varun_Shakya

MVP

21-08-2020

Use jquery or javascript functions(document.cookie) to get the cookie value.

Add any class or id in div tag and with help of that identifier add the value in div tag[  $("#id").val()  ].

Answers (3)

Answers (3)

Andrei_Dantsou

21-08-2020

Hi @viki1101,

Basically, the code written using JavaScript Use-Api is converted to Java (please see https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino for reference) and thus it is executed at a server side as well as Sightly (please see accepted solution here https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/sightly-javascript-use-imp...). If CDN and/or Dispatcher are used for caching content (the most likely), the server side approach for displaying cookies is not suitable - after html of a rendered page is cached, the back-end on Publish won't be hit to get the actual value and the cached one will be displayed.

I'd recommend following the fully front-end approach here - to move retrieval of cookies to JS stored in a clientlib. After the value is retrieved, it can be appended to necessary html element as described here https://api.jquery.com/append/

Regards

Arun_Patidar

MVP

22-08-2020

You should handle cookie from clientside.

The reason is if page is cached then your request will not go to server side to execute code based on cookie.

Nikhil-Kumar

MVP

22-08-2020

@viki1101 
Try rendering it on the server side itself to retrieve the cookie and then append to some html tag.
This might solve your issue.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>append demo</title>
<style>
p {
background: yellow;
}
</style>
</head>
<body>
 
<p>I would like to say: </p>
 
<script>
$( "p" ).append( "<strong>Hello</strong>" );
</script>
 
</body>
</html>