下划线.js不适用于 HTML 中的<和>

underscore.js not working with < and > in html

本文关键字:中的 js 不适用 适用于 HTML 下划线      更新时间:2023-09-26

我正在使用下划线.js我在<%= name %>中遇到<和>问题。它们会自动替换为 <和>这导致我的代码不起作用。

我的索引.html:

<div id="underscore">
   <%= name %>
</div>

我的脚本:

var source   = $("#underscore").html();
var compiled = _.template(source);
var html = compiled({name: 'pepe'});
$("#underscore").html(html);

我修复了将此行添加到我的脚本中的问题(在 var 编译之前)并且工作正常

source = source.replace("&lt;","<");
source = source.replace("&gt;",">");

还有其他方法可以解决我的问题吗?

传统上,人们使用带有非JavaScript"类型"属性的<script>标签来嵌入模板。

<script id=underscore type=text/underscore>
  <%= name %>
</script>

浏览器将完全忽略结束</script>标记之前的所有内容。 您仍然可以将其作为<script>.innerHTML获取。