Reputation: 4333
I have a View that's model includes a small array. I want to output each array item wrapped in it's own <span>
, but when using the template helper in the template, I am getting the html chars escaped and it's outputted as <span>
Is there a way to prevent that from happening?
templateHelpers: function () {
return {
tagsHelper: function(){
var t = "";
this.tags.forEach(function(tag)
{
t+="<span>"+tag+"</span>";
});
return t;
},
}
},
and
<script type="text/template" id="font-list-item">
<td class="alias"><%- name %></td>
<td class="tags"><%- tagsHelper() %></td>
</script>
Upvotes: 2
Views: 577
Reputation: 897
Marionette uses underscore.js#templates behind the scenes to render it's templates. This template-system supports two ways of printing variables:
<%- variable %>
will output the variable escaped <%= variable %>
will output the variable unescapedIn your first example, you're using the escaped one (<%- ... %>
) which will output characters like:
<
as <
>
as >
&
as &
In order to be able to use the templateHelper in your example, you should render the tagsHelper
as <td class="tags"><%= tagsHelper() %></td>
(since it contains HTML which shouldn't be escaped).
However, in some situations you should be aware of possible XSS attacks while rendering variables unescaped. Therefore, it's better make sure the variables themselves are escaped. Your example could be rewritten as:
templateHelpers: function () {
return {
tagsHelper: function(){
var t = "";
this.tags.forEach(function(tag) {
// note the _.escape(..) below
t += "<span>" + _.escape(tag) + "</span>";
});
return t;
}
}
}
Howeverrr, I'd suggest to go for your second solution, with the html-markup inside your template, since it makes more sense to type html insde a template :-) Note the tag
itself should be escaped though (so use the <%- ... %>
syntax)
Upvotes: 4
Reputation: 4333
I was able to get it to work with a different approach, using an in-template logic block, but I would still really like to know how to fix the original problem, in case I find myself needing to use templateHelpers in the future.
<script type="text/template" id="font-list-item">
<td class="alias"><%- name %></td>
<td class="tags">
<% tags.forEach(function(tag){ %>
<span><%= tag %></span>
<% }); %>
</td>
</script>
Upvotes: 0