2016-11-10 64 views
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?

回答

1

嘗試訪問JavaScript中的未定義變量將導致例外,除非您使用typeof。沒有真正的解決方法。

但是,如果換你的整個模板在另一個對象,然後使用if你想應該的工作方式(作爲財產undefined上的對象結果中丟失,也不例外):

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> 
    <% } %> 

... 
+0

另一種可能性'的」 ARIA隱藏= 「真」>'這可以讓你跳過'if'條件 –

+0

這並不會產生同樣的效果,因爲當變量不存在時,最初的想法並不是顯示''。 – fstanis

相關問題