Can't easily test this right now, but wouldn't something like the following work?
{{#items:i}}
{{name}} {{ i < (items.length-1) ? "," : "" }}
{{/items}}
質問
Basically I want to this: In Mustache templating is there an elegant way of expressing a comma separated list without the trailing comma? in a Ractive template.
For the object
{
"items": [
{"name": "red"},
{"name": "green"},
{"name": "blue"}
]
}
I want to produce "red, green, blue"
I want to know if I am at the last item, so I can know whether to print the separator. Something like:
{{#items:i}}{{name}} {{#i.is_last}},{{/i}}{{/items}}
解決
Can't easily test this right now, but wouldn't something like the following work?
{{#items:i}}
{{name}} {{ i < (items.length-1) ? "," : "" }}
{{/items}}
他のヒント
Can confirm that Stephen Thomas' answer works. Another option would be to join the array items like so:
ractive = new Ractive({
el: 'body',
template: '{{ items.map( getName ).join( ", " ) }}',
data: {
items: [{ name: 'red' }, { name: 'green' }, { name: 'blue' }],
getName: function ( item ) {
return item.name;
}
}
});
I actually wanted a solution that would allow me to put something more complicated instead of a comma, say, a DOM element. I figured out (another) method that works.
{{#items:i}}
{{name}}{{#(i<(items.length-1))}}, {{/end}}
{{/items}}
Recently @index
and @last
magic variables are introduced, so the example now becomes more readable:
{{#items}}
{{.name}}{{#@index !== @last}}, {{/}}
{{/}}