In my html page I would like to loop through the properties returned by my Java class but do it under <script>
tag.
Currently my html page has this:
<div id="map_wrapper">
<div data-sly-use.ev="Foo"
class="mapping"
id="${ev.googleClass || ''"
>
</div>
</div>
<script>
....
var markers = [
['Bondi Beach', -33.890542, 151.274856],
['Coogee Beach', -33.923036, 151.259052],
['Cronulla Beach', -34.028249, 151.157507],
['Manly Beach', -33.80010128657071, 151.28747820854187],
['Maroubra Beach', -33.950198, 151.259302]
];
.....
</script>
My Java Class has following getters:
//returns [0] = "something, -33.89, 151.2" [1] = "beach, -33.9, 15.02" etc.
public List<String> getVals() {
return vals;
}
public String getGoogleClass() {
if (vals.size() == 0)
return "";
return "map_canvas";
}
Question
How can I replace the values in markers
variable in <script>
tag with values returned from getVals()
?
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