簡體   English   中英

Javascript-檢查文本/模板腳本中是否存在字段

[英]Javascript - Check if field exists inside text/template script

我有一個text/template類型的腳本,其中顯示了一些從ElasticSearch數據庫檢索到的值。 我的腳本如下所示:

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

但是,有些時候未定義此突出顯示值,而我想顯示_source.field1 我最初的猜測是添加一個try catch,但這是行不通的:

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

以后編輯:高亮並不總是可用。 而是_source字段始終可用。

另外,我正在使用backbone.js views.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"
    ]
  }
}

還有其他建議嗎?

我認為在我們的情況下,try..catch是開銷,您可以使用邏輯表達式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM