How can you view list items under <script>?

In my html page, I would like to iterate over the properties returned by my Java class, but do so under the tag <script>

.

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 the 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 do I replace the values ​​in a variable markers

in a tag with <script>

values ​​returned from getVals()

?

+3


source to share


2 answers


Not. To create JSON in Java, I would use JSONStringer or server-side JavaScript, which would be JSON.stringify

so as not to do this with a template.

For example, a template file might do something like this:

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

      

And the corresponding logic.js file will do:



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

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

      

Better yet, for good separation of concerns, it would be to avoid inline scripts altogether, which would also eliminate the troublesome context = "unsafe" here. Your best bet is to put this in a data attribute that is exactly made for this. So your template will look like this:

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

      

It might seem like JSON is getting unnecessary escaping, but you don't need to think about them, HTML will handle them just fine. You can try my example above with a real life REPL environment: https://github.com/Adobe-Marketing-Cloud/aem-sightly-repl

+5


source


You can create a java slingservlet that provides data and hit the servlet with ajax inside a script tag.



Here's a little tutorial

-2


source







All Articles