Passing cookie value to data-sly-use without using Use-API

viki1101

03-09-2020

Hello Community - I wanted to use the cookie or sessionstorage value in clientside using Javascript or Jquery (Not USE-API as this will be executed in serverside) and pass the value as one of the parameter(Instead of 'xyz') in data-sly-use & data-sly-test as well. Please let me know how to achieve this in HTL without using Use-API.

<div data-sly-use.testobj="${'com.aem.test.core.models.productInfo' @ cookieVal=xyz" data-sly-unwrap>

</div>

Any help in this is highly appreciated.

Accepted Solutions (1)

Accepted Solutions (1)

surabhikatiyar

Employee

06-09-2020

The cookie value cannot be sent through Javascript to the WCMPojo, because the javascript section loads after the HTML/JSP has been loaded. So, even if you fetch the cookie value using Javascript it will never reach the WCMPojo class until you reload via some dynamic template binding.

 

The other options are:-

1. Directly fetch the cookie in WCMPojo class using the request object

 

Cookie[] cookies = request.getCookies();
for (Cookie cookie: cookies) {
    String value = cookie.getValue();
}
 
2. Use the  USE-API
 

-------- script.js -------------

// Server-side JavaScript to get Coookie

use(function () {

var cookie = request.getCookie("wcmmode");

var cookieFound=false;

if(cookie!=null && cookie.value=="edit"){

cookieFound = true;

}

return {

cookieVal: cookie.value,

cookieFound:cookieFound

};

});

-------- Sightly code --------------

<sly data-sly-use.cObj="script.js" data-sly-test="${cObj.cookieFound }">

${cObj.cookieVal}

</sly>

Answers (1)

Answers (1)

Nupur_Jain

MVP

04-09-2020

Hi @viki1101 

 

If you want to pass value from clientside to serverside, session storage can never be an option as it is clientside and can not be accessed serverside.

 

You can use cookie as the cookie values are passed to serverside via "cookie" request header. In order to get the value of cookie.  You can use use api to get cookie value and then pass it to your sling model like this

 

cookie.js 

 

use(function () {

    var cookieValue = request.getCookie("cookiename");

    return {

       cvalue : cookieValue

    };

});

 

HTL

 

<div data-sly-use.cookie="cookie.js" data-sly-use.testobj="${'com.aem.test.core.models.productInfo' @ cookieVal=cookie.cvalue" data-sly-unwrap>

</div>

 

 

Hope it helps!

Thanks

Nupur