I am using Underscore JS for AEM component creation (Using HTL). The below snippet is not working for the page properties. Can someone tell how to address this?
<script type="text/template" id="testView">
<% _.each(test, function(test) { %>
<div class="templatetest">
**<sly data-sly-test=" <% ${properties.displayimages} %> ">**(This line of code doesn't work)
<img src="<%= test.image %>" class="w-full" alt="">
</sly>
</div>
The reason that line doesn't work is that you are using a mix of two different things that don't belong together, neither of which by itself is sufficient to produce any output. The things in question are (1) the Underscore
_.templateevaluation tag and (2) an ES6 template literal placeholder. Let's discuss these in order.Underscore's
_.templateoffers three types of tags:<% ... %>, which you used in the problematic line. This lets you insert arbitrary JavaScript code between the literal parts of your template, like you did on the first line with_.each(test, function(test) {. This tag produces no output unless you call theprint()function inside of it.<%= ... %>. This tag let you insert a JavaScript expression, which will be converted to string. This string is included verbatim in the output. You have used this on the next line withtest.image.<%- ... %>. This is like the interpolation tag except that it also performs HTML escaping.Your faulty line uses the evaluation tag without calling
print. This is the first reason why yourdata-sly-testattribute remains empty.ES6 template literals are a new feature of the JavaScript language that let you do this:
instead of this:
The
${...}part of this notation is called a placeholder, and you are also using this notation on the faulty line. However, there is no ES6 template literal anywhere to be seen; your placeholder does not appear between backticks. Outside of a template literal, this notation has no special meaning; it is the expression$(maybe the jQuery object or maybe justundefined) followed by a code block. The expression is a no-op, and in your case, so is the code block.In order to use
properties.displayimagesas the value of thedata-sly-testattribute, the following notations would all work:Note that this requires the
propertiesobject to be in scope at this line of the template. It is impossible to tell from the template alone whether this is the case; it depends both on the data that you are passing to the template and on the way in which you compile the template. Ifpropertiesis not in scope, this is a third mistake you need to address.