0
我正在使用Lodash模板。使用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?
另一種可能性'的」 ARIA隱藏= 「真」>'這可以讓你跳過'if'條件 –
這並不會產生同樣的效果,因爲當變量不存在時,最初的想法並不是顯示''。 – fstanis