Expand my Community achievements bar.

SOLVED

Load a sightly condition based on a cookie check

Avatar

Level 1

Hello Community,
Wanted to understand if there is a possibility in AEM to check a cookie and load a sightly tag.

My use case

<sly data-sly-test="${properties.something == 'true'}">

<script>
Cookie condition check only if true execute the below

<div data-sly-test="${properties.something }" data-sly-unwrap>

            <script type="text/javascript"  src="${properties.script}"></script>

        </div>

</script >

</sly>

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

I am not sure if you can do it from front end because the sightly code. But you can do it with Server side JS 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>



Arun Patidar

View solution in original post

4 Replies

Avatar

Former Community Member

This is very easy. Use Sling Model and use Java logic to check a cookie. Setting and Reading Cookies : Cookie « Servlets « Java

Then set a field in the Sling Model based on the value.

Avatar

Level 1

Thanks Joeb,
I understand we could do a condition from backend , but we are using CDN for caching our pages . So whatever is cached first that experience would be shown, that is the reason we are looking for a front end solution.

Avatar

Level 5
Sesha - Were you able to find the solution for your scenario?

Avatar

Correct answer by
Community Advisor

I am not sure if you can do it from front end because the sightly code. But you can do it with Server side JS 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>



Arun Patidar