Javascript - Check if field exists inside text/template script

435 Views Asked by At

I have a script of type text/template in which I display some values retrieved from an ElasticSearch database. My script looks like this:

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

However, there are times when this highlight value is not defined and I would like to display _source.field1 instead. My initial guess was to add a try catch, but that wouldn't work:

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

Later edit: highlight is not always going to be available. Instead the _source field is always available.

In addition, I am using backbone.js, and inside views.js I have defined:

    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;
        }
     });

The model is:

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

Any other suggestions?

1

There are 1 best solutions below

0
On BEST ANSWER

I think in our case try..catch is overhead, you can use 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>