【发布时间】:2017-03-24 21:29:09
【问题描述】:
我正在使用 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) { %>时,它会说标题是未定义的。
有没有更简单的方法来检查变量是否存在,使用不会弄乱 html 的 lodash 模板?
【问题讨论】:
标签: javascript lodash template-engine