How can list elements be looped under <script> in sightly?

匆匆过客 提交于 2019-12-06 03:45:17

No. For generating JSON, in Java I'd use the JSONStringer, or in server-side JavaScript that would be JSON.stringify, in order to avoid doing that with the template.

For example, the template file could do something like that:

<script data-sly-use.logic="logic.js">
    var markers = ${logic.json @ context='unsafe'}
</script>

And the corresponding logic.js file would do:

use(function () {
    var myObj = {
        foo: "bar",
        arr: [1,2,3,4,5,6,7,8,9,10]
    };

    return {
        json: JSON.stringify(myObj)
    };
});

Even better for a good separation of concerns would be to avoid inline scripts altogether, which would also remove the worrying context='unsafe' that's needed here. The best is usually to put this into a data attribute, which are precisely made for that. So your template would then look as follows:

<div id="map_wrapper"
     data-sly-use.logic="logic.js"
     data-markers="${logic.json}">
    ...
</div>

It might look that the JSON gets unnecessary escaping, but you don't need to mind about them, HTML will handle them just fine. You can try out my above example with the REPL live Sightly evaluation environment: https://github.com/Adobe-Marketing-Cloud/aem-sightly-repl

You could create a java slingservlet that exposes the data, and hit the servlet with ajax inside the script tag.

Here's a bit of a guide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!