我正在使用 Lodash 模板。
模板:
<script type="text/template" id="example-template">
<% if (typeof(leadingIconClass) !== "undefined") { %>
<span class="glyphicon glyphicon-<%= leadingIconClass %>" aria-hidden="true"></span>
<% } %>
<% if (typeof(headline) !== "undefined") { %>
<strong><%= headline %></strong>
<% } %>
<%= message %>
<% if (typeof(mainHTML) !== "undefined") { %>
<div class="group" style="margin-top: 20px;">
<%= mainHTML %>
</div>
<% } %>
</script>
提供给模板的数据:
var data = {
message: 'Are you sure?'
};
编译模板并附加到容器:
$container.prepend(_.template($("#example-template").html())(data));
我上面写的方法(来自:https://stackoverflow.com/a/7230755/83916)效果很好,但我真的不喜欢 if
<% if (typeof(headline) !== "undefined") { %>
中的语句.但是当我简单地写 <% if (headline) { %>
,它会说标题未定义。
有没有更简单的方法来检查变量是否存在,使用 lodash 模板,不会弄乱 html?
最佳答案
尝试访问 JavaScript 中 undefined variable 将导致异常除非您使用typeof
。没有真正的解决办法。
但是,如果您将整个模板包装在另一个对象中,则可以按照您想要的方式使用 if
(因为对象缺少属性会导致 undefined
,也不异常(exception)):
var data = {
data: {
message: 'Are you sure?'
}
};
然后在你的模板中:
<script type="text/template" id="example-template">
<% if (data.leadingIconClass) { %>
<span class="glyphicon glyphicon-<%= data.leadingIconClass %>" aria-hidden="true"></span>
<% } %>
...
关于javascript - 使用 lodash 模板,如何检查变量是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534616/