phi*_*kim 3 html javascript lodash
我想使用lodash.template()创建一个html代码,但结果不是我预期的.
var a = '<td>a</td>';
var expected = '<tr><td>a</td></tr>';
var actual = _.template('<tr><%- a %></tr>', {a: a});
console.log(actual);
"<tr><td>a</td></tr>"
Run Code Online (Sandbox Code Playgroud)
因此填充的文本a已被转义.
我怎样才能得到结果expected?
我可以设置options.escape,但不知道如何使用此选项.
谢谢!
您可以使用<%= a %>或print在评估上下文中进行记录,但不建议以此方式生成HTML以确保安全性.
var actual = _.template('<tr><% print(a) %></tr>', {a: a});
// or
var actual = _.template('<tr><%= a %></tr>', {a: a});
Run Code Online (Sandbox Code Playgroud)