我想使用 Handlebars 在无序列表中显示一系列数据,分为“标题”和“文章”。然而,有些文章会包含不同的 HTML 标签,比如 <a>
链接的标签。如果您看一下下面的代码,当数据附加到 DOM 时,它不会显示类似“您可以在此处阅读更多相关信息”的链接,而是显示实际的 HTML anchor 标记。有谁知道解决这个问题的方法吗?
<div id="myDiv"></div>
考虑以下模板:
<script id="my-template" type="text/x-handlebars-template">
<div style='margin: 20px'>
<ul style='list-style-type: none; width:500px'>
<h4 style='padding:10px; overflow: auto'>General Credit</h4>
{{#each this}}
<li style='padding:10px; overflow: auto'>
<h3>{{title}}</h3>
<p>{{article}}</p>
</li>
{{/each}}
</ul>
</div>
</script>
我的 JavaScript 看起来像这样:
//Data for Articles
var articleData = [
{
title: "My title here",
article: "You can learn more about it <a href='https://www.google.com'>here</a>"
}
];
//Get Template From Script Tag
var source1 = $("#my-template").html();
//Compile Template
var template1 = Handlebars.compile(source1);
$("#myDiv").append(template1(articleData));
最佳答案
您应该使用三重花括号:
<li style='padding:10px; overflow: auto'>
<h3>{{{title}}}</h3>
<p>{{{article}}}</p>
</li>
这样 Handlebars 就不会转义字符串中的 HTML 代码。
Here引用。
干杯
关于javascript - Handlebars JS : Including <li>, <br>,以及数据中的其他 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39773442/