AEM 6.x:如何将HTL变量传递至clientlib/JS?
把HTL属性传递给ClientLib JavaScript的几种方案
我来给你分享几个实用的办法,帮你把HTL里的${properties.myCustomProperty}传递给你的myhost.mycustomJS clientlib:
方法1:利用HTML Data属性
这是最直观且符合规范的方式,把数据挂载到DOM元素上,再让JS读取:
第一步:在HTL中添加带data属性的元素
你可以在页面的容器元素(比如组件根元素或页面固定位置)上添加自定义data属性:
<!-- 可以放在组件的根元素里,或者页面的某个固定位置 --> <div class="custom-component-wrapper" data-custom-property="${properties.myCustomProperty}"></div> <!-- 你的ClientLib加载代码 --> <sly data-sly-use.clientLib="${'/libs/granite/sightly/templates/clientlib.html'}" data-sly-unwrap /> <sly data-sly-call="${clientLib.js @ categories='myhost.mycustomJS'}" data-sly-unwrap />
第二步:在myCustomJS中读取数据
在你的clientlib JS文件里,通过DOM选择器获取元素,再读取data属性:
// 获取目标元素 const componentWrapper = document.querySelector('.custom-component-wrapper'); // 读取data属性(dataset会自动把连字符转成驼峰,比如data-custom-property对应dataset.customProperty) const myCustomValue = componentWrapper?.dataset.customProperty; // 后续使用这个值 if (myCustomValue) { console.log('获取到的属性值:', myCustomValue); // 执行你的业务逻辑 }
方法2:通过内联脚本定义全局变量
如果需要传递的数据比较直接,也可以在加载clientlib之前,先输出内联脚本把HTL变量赋值给全局对象:
第一步:在HTL中输出内联脚本
注意要在clientlib加载之前定义全局变量,并且一定要用@ context='scriptString'转义特殊字符,避免语法错误或XSS风险:
<!-- 先定义全局变量 --> <script> window.myAppData = { customProperty: "${properties.myCustomProperty @ context='scriptString'}" }; </script> <!-- 再加载你的ClientLib --> <sly data-sly-use.clientLib="${'/libs/granite/sightly/templates/clientlib.html'}" data-sly-unwrap /> <sly data-sly-call="${clientLib.js @ categories='myhost.mycustomJS'}" data-sly-unwrap />
第二步:在myCustomJS中直接使用全局变量
在你的clientlib JS里,直接访问这个全局对象即可:
// 读取全局变量 const myCustomValue = window.myAppData?.customProperty; if (myCustomValue) { console.log('获取到的属性值:', myCustomValue); // 你的业务逻辑代码 }
额外注意事项
- 如果传递的是复杂JSON对象,可以用
${JSON.stringify(properties.myCustomObject) @ context='unsafe'},但要确保数据是可信的,避免XSS风险 - 全局变量命名尽量独特,比如加上项目前缀(比如
myAppData而非data),避免和其他脚本冲突 - Data属性命名要遵循HTML规范:全小写,用连字符分隔(比如
data-custom-property)
内容的提问来源于stack exchange,提问作者mrjayviper
相关产品推荐
相关产品推荐

