0

我有一個類型爲text/template的腳本,其中顯示從ElasticSearch數據庫檢索到的一些值。我的腳本是這樣的:Javascript - 檢查文本/模板腳本中是否存在字段

<script type="text/template" id="script1"> 
    <div style="color:black;"><%= highlight.field1 %></div> 
</script> 

然而,有些時候沒有定義這個亮點價值,我想顯示_source.field1代替倍。我最初的猜測是增加一個嘗試捕捉,但是這是行不通的:

<script type="text/template" id="script1"> 
    <div style="color:black;"><%= try{ highlight.field1 } catch(e) { _source.field1 } %></div> 
</script> 

後來編輯:亮點是並不總是可用。相反,_source字段始終可用。

另外,我使用backbone.js了,裏面views.js我已經定義:

DocumentView = Backbone.View.extend({ 
     tagName : "div", 
     className: "document well", 
     initialize: function() { 
      this.model.bind('change', this.render, this); 
      this.model.bind('destroy', this.remove, this); 
      }, 
     template: [_.template($("#script1").html())], 
     render : function() { 
      this.$el.html(this.template[0](this.model.toJSON())); 
      return this; 
     } 
    }); 

的模型是:

{ 
    "_index": "index1", 
    "_type": "doc", 
    "_id": "id1", 
    "_score": 10.139895, 
    "_source": { 
    "field1": "fieldValue1" 
    }, 
    "highlight": { 
    "field1": [ 
     "highlightedFieldValue1" 
    ] 
    } 
} 

任何其他建議?

+0

什麼是「行不通」的意思嗎?你給模板的數據看起來像什麼? – 2014-12-01 17:52:10

+0

當腳本解釋爲「意外令牌嘗試」時出現錯誤。 – Crista23 2014-12-01 17:58:46

+0

我得到同樣的問題,如果我嘗試使用if語句,「意外的標記如果」 – Crista23 2014-12-01 18:15:55

回答

2

我認爲,在我們的例子在try..catch是開銷,可以使用logical expressions

<script type="text/template" id="script1"> 
    <div style="color:black;"> 
     <% if (typeof highlight !== 'undefined' && highlight.field1) { %> 
     <%= highlight.field1.length ? highlight.field1[0] : highlight.field1 %> 
     <% } else if (typeof _source !== 'undefined' && _source.field1) { %> 
     <%= _source.field1 %> 
     <% } %> 
    </div> 
    </script> 
相關問題