我有一个字符串e的列表。g. items = ["red", "green", "blue", ...]
,我想使用模板来获取
"should": [
{
"term": {
"mycolor": "red"
}
},
{
"term": {
"mycolor": "green"
}
},
{
"term": {
"mycolor": "blue"
}
},
...
]
现在我在努力
"should": [
{{#items}}
{
"term": {
"mycolor" : "{{.}}"
}
},
{{/items}}
]
但它不起作用,因为结尾会有一个逗号。我怎样才能去掉后面的逗号来使它工作?
2条答案
按热度按时间5q4ezhmt1#
我自己找到了答案。Moustache是一个“无逻辑”的模板工具,所以似乎没有比我在这里尝试的更好的选择了。如果您有更好的想法,请添加答案或评论。
要呈现多个term子句并处理结尾的逗号,我可以
其中items是这样的对象列表
使用
^
操作符,即“倒置部分”,模板知道当“last”出现时不呈现逗号。更高级的案例
如果你必须在一些现有的条款上添加这个条款列表,e。例如,在“myssize”之上添加这些“mycolor”术语
您将需要处理两个列表都为空的情况,并处理是否在它们之间添加逗号i。例如,如果“mysize”列表不为空,则“mycolor”应该有一个尾随逗号,否则不是。在这种情况下,我们需要根据第二个列表是否为空来呈现一个逗号。如果我们使用第二个列表
sizes
作为标签,它不起作用,因为Moustache将呈现逗号N次,其中N是sizes
的长度。AFAIK没有办法基于非空列表渲染 once。因此,我必须引入另一个参数sizesExist
,并在代码中设置它。kgsdhlau2#
在这个特定的例子中,可以使用terms query和mustache
toJson
运算符来展开colors数组