Link with printed parameter 这给了我一个意外的标识符错误。我尝试过在第二个 %> 周围进行各种扩展,但它只是按字面打-6ren">
gpt4 book ai didi

javascript - 在下划线模板三元中打印变量

转载 作者:行者123 更新时间:2023-11-28 18:09:13 24 4
gpt4 key购买 nike

是否可以在评估过程中打印下划线模板中的变量。

<a href="<%=data.active ? 'the/url' : 'another/url/<%='data.id'%>'%>">Link with printed parameter</a>

这给了我一个意外的标识符错误。我尝试过在第二个 %> 周围进行各种扩展,但它只是按字面打印。我还尝试使用 print() 别名,以便编译器不会因重复的 %> 感到困惑,但是没有运气。有没有办法在三元中做到这一点?

最佳答案

当您不尝试使用嵌套模板时,工作不会出现问题。

var source = document.getElementById("testTemplate").innerHTML;
var testTemplate = _.template(source);

document.getElementById("target1").innerHTML = testTemplate({
data: {
active: false,
id: 12345
}
});

document.getElementById("target2").innerHTML = testTemplate({
data: {
active: true,
id: 67890
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<script type="text/template" id="testTemplate">
<a href="<%= data.active ? 'the/url' : 'another/url/' + encodeURIComponent(data.id) %>">Link with printed parameter</a>
<p>The URL is "<%= data.active ? 'the/url' : 'another/url/' + encodeURIComponent(data.id) %>".</p>
<hr>
</script>

<div id="target1"></div>
<div id="target2"></div>

注意:即使您的 data.id 通常是严格的数字,但在构建 URL 时最好只使用 encodeURIComponent 。干净地转义数据是一个值得养成的好习惯。

关于javascript - 在下划线模板三元中打印变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41986197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com