Javascript - 检查文本/模板脚本中是否存在字段
问题描述:
我有一个类型为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"
]
}
}
任何其他建议?
答
我认为,在我们的例子在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>
什么是“行不通”的意思吗?你给模板的数据看起来像什么? – 2014-12-01 17:52:10
当脚本解释为“意外令牌尝试”时出现错误。 – Crista23 2014-12-01 17:58:46
我得到同样的问题,如果我尝试使用if语句,“意外的标记如果” – Crista23 2014-12-01 18:15:55