Expand my Community achievements bar.

SOLVED

HTL Expression in Javascript

Avatar

Level 5

Hello Community - I am working on a component which uses the sling model to get the required values for the properties that is working as expected. My question here is, I need to use the values I received from Sling Model in javascript (Included as a clientlib in the component). 

E.g. <sly data-sly-use.productData="com.xxx.aem.models.ProductData"></sly>

 

${productData.prodDescription @ context='unsafe'} - Can this be used directly used in clientlibs (Not USE API) ?

ClientLibrary:

var prodDetails = '${productData.prodDescription @CONTEXT='unsafe'}';

--------------------------------------------

Or should I assign this in HTL first like: <sly data-sly-test.prodDetails ="${productData.prodDescription @ context='unsafe'}"></sly> and then use it in javascript as below?

var prodDetails = '${prodDetails}'; - I already set the context in HTL, so I didn't use it here.

 

Also could somebody clarify in which scenario should the context as "scriptString" or "unsafe" be used?  As I see both are being used in variable assignment in JS.

 

 

 

 

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @v1101 ,

 

To fetch the values from HTML to JS, you can add the Model value into the data attribute and in JS you can initialize the module and access it.

HTML:

data-modelValue='${modelObject.modelValue}'

JS:

function init($, $module) {

const dom = {

modelValue: $module.data(modelValue)

}

}

 

We have different context elements and

  • unsafe - use this at your own risk, this disables XSS protection completely
  • scripting - Applies JavaScript string escaping

Reference: https://github.com/adobe/htl-spec/blob/master/SPECIFICATION.md#12-available-expression-options

 

Thanks,

Kiran Vedantam.

View solution in original post

3 Replies

Avatar

Community Advisor

Hi @v1101 

Set the value to a data attribute and get it in client side javascript.

HTL:

<div data-prod-desc="${productData.prodDescription}" > ... </div>

Javascript:

$("div[data-prod-desc]").data("prodDesc")

-AG

Avatar

Correct answer by
Community Advisor

Hi @v1101 ,

 

To fetch the values from HTML to JS, you can add the Model value into the data attribute and in JS you can initialize the module and access it.

HTML:

data-modelValue='${modelObject.modelValue}'

JS:

function init($, $module) {

const dom = {

modelValue: $module.data(modelValue)

}

}

 

We have different context elements and

  • unsafe - use this at your own risk, this disables XSS protection completely
  • scripting - Applies JavaScript string escaping

Reference: https://github.com/adobe/htl-spec/blob/master/SPECIFICATION.md#12-available-expression-options

 

Thanks,

Kiran Vedantam.