Marionette templateHelper 正在转义 html 个字符
Marionette templateHelper is escaping html chars
我有一个模型包含一个小数组的视图。我想输出包裹在它自己的 <span>
中的每个数组项,但是在模板中使用模板助手时,我得到了 html 字符转义,它输出为
有没有办法防止这种情况发生?
templateHelpers: function () {
return {
tagsHelper: function(){
var t = "";
this.tags.forEach(function(tag)
{
t+="<span>"+tag+"</span>";
});
return t;
},
}
},
和
<script type="text/template" id="font-list-item">
<td class="alias"><%- name %></td>
<td class="tags"><%- tagsHelper() %></td>
</script>
我能够使用模板内逻辑块以不同的方法让它工作,但我仍然很想知道如何解决原来的问题,以防我发现自己需要使用 templateHelpers将来。
<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>
Marionette 在幕后使用 underscore.js#templates 来渲染它的模板。该模板系统支持两种打印变量的方式:
<%- variable %>
将输出转义的变量
<%= variable %>
将输出未转义的变量
在您的第一个示例中,您使用的是转义字符 (<%- ... %>
),它将输出如下字符:
<
作为 <
>
作为 >
&
作为 &
- 等等
为了能够在您的示例中使用 templateHelper,您应该将 tagsHelper
呈现为 <td class="tags"><%= tagsHelper() %></td>
(因为它包含不应转义的 HTML)。
但是,在某些情况下,您应该注意在呈现未转义变量时可能发生的 XSS 攻击。因此,最好确保变量本身被转义。您的示例可以重写为:
templateHelpers: function () {
return {
tagsHelper: function(){
var t = "";
this.tags.forEach(function(tag) {
// note the _.escape(..) below
t += "<span>" + _.escape(tag) + "</span>";
});
return t;
}
}
}
但是,我建议您使用第二个解决方案,在模板中使用 html-标记,因为在模板中键入 html 更有意义:-) 注意tag
本身应该被转义(所以使用 <%- ... %>
语法)
我有一个模型包含一个小数组的视图。我想输出包裹在它自己的 <span>
中的每个数组项,但是在模板中使用模板助手时,我得到了 html 字符转义,它输出为
有没有办法防止这种情况发生?
templateHelpers: function () {
return {
tagsHelper: function(){
var t = "";
this.tags.forEach(function(tag)
{
t+="<span>"+tag+"</span>";
});
return t;
},
}
},
和
<script type="text/template" id="font-list-item">
<td class="alias"><%- name %></td>
<td class="tags"><%- tagsHelper() %></td>
</script>
我能够使用模板内逻辑块以不同的方法让它工作,但我仍然很想知道如何解决原来的问题,以防我发现自己需要使用 templateHelpers将来。
<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>
Marionette 在幕后使用 underscore.js#templates 来渲染它的模板。该模板系统支持两种打印变量的方式:
<%- variable %>
将输出转义的变量<%= variable %>
将输出未转义的变量
在您的第一个示例中,您使用的是转义字符 (<%- ... %>
),它将输出如下字符:
<
作为<
>
作为>
&
作为&
- 等等
为了能够在您的示例中使用 templateHelper,您应该将 tagsHelper
呈现为 <td class="tags"><%= tagsHelper() %></td>
(因为它包含不应转义的 HTML)。
但是,在某些情况下,您应该注意在呈现未转义变量时可能发生的 XSS 攻击。因此,最好确保变量本身被转义。您的示例可以重写为:
templateHelpers: function () {
return {
tagsHelper: function(){
var t = "";
this.tags.forEach(function(tag) {
// note the _.escape(..) below
t += "<span>" + _.escape(tag) + "</span>";
});
return t;
}
}
}
但是,我建议您使用第二个解决方案,在模板中使用 html-标记,因为在模板中键入 html 更有意义:-) 注意tag
本身应该被转义(所以使用 <%- ... %>
语法)