Reputation: 1
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>
Upvotes: 0
Views: 220
Reputation: 4381
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 _.template
evaluation tag and (2) an ES6 template literal placeholder. Let's discuss these in order.
Underscore's _.template
offers 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 the print()
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 with test.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 your data-sly-test
attribute remains empty.
ES6 template literals are a new feature of the JavaScript language that let you do this:
`Hello, ${name}.`
instead of this:
'Hello, ' + name + '.'
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 just undefined
) 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.displayimages
as the value of the data-sly-test
attribute, the following notations would all work:
<% print(`${properties.displayimages}`) %>
<% print(properties.displayimages) %>
<%= `${properties.displayimages}` %>
<%= properties.displayimages %>
Note that this requires the properties
object 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. If properties
is not in scope, this is a third mistake you need to address.
Upvotes: 0