在Moustache模板中,有没有一种优雅的方式来表示逗号分隔的列表而没有尾部的逗号? [英] In Mustache templating is there an elegant way of expressing a comma separated list without the trailing comma?

查看:90
本文介绍了在Moustache模板中,有没有一种优雅的方式来表示逗号分隔的列表而没有尾部的逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Mustache模板库,并尝试生成一个以逗号分隔的列表,而没有结尾的逗号,例如

I am using the Mustache templating library and trying to generate a comma separated list without a trailing comma, e.g.

红色,绿色,蓝色

red, green, blue

给定结构,用结尾逗号创建列表很简单

Creating a list with the trailing comma is straightforward, given the structure

{
  "items": [
    {"name": "red"},
    {"name": "green"},
    {"name": "blue"}
  ]
}

和模板

{{#items}}{{name}}, {{/items}}

这将解决

红色,绿色,蓝色

red, green, blue,

但是,如果没有结尾的逗号,我看不到一种优雅的表达方式.在将其传递到模板之前,我总是可以用代码生成列表,但是我想知道库是否提供了另一种方法,例如允许您检测它是否是模板中列表的最后一项.

However I cannot see an elegant way of expressing the case without the trailing comma. I can always generate the list in code before passing it into the template, but I was wondering whether the library offers an alternative approach such as allowing you to to detect whether it is the last item in a list within the template.

推荐答案

可疑,胡子演示使用first属性几乎可以向您显示,您必须在JSON数据中包含逻辑以弄清楚何时放置逗号.

Hrm, doubtful, the mustache demo pretty much shows you, with the first property, that you have to have the logic inside the JSON data to figure out when to put the comma.

所以您的数据看起来像这样:

So your data would look something like:

{
  "items": [
    {"name": "red", "comma": true},
    {"name": "green", "comma": true},
    {"name": "blue"}
  ]
}

和您的模板

{{#items}}
    {{name}}{{#comma}},{{/comma}}
{{/items}}

我知道这并不优雅,但是 胡子非常轻巧,不提供此类功能.

I know it's not elegant, but as mentioned by others Mustache is very lightweight and does not provide such features.

这篇关于在Moustache模板中,有没有一种优雅的方式来表示逗号分隔的列表而没有尾部的逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆