在 Mustache 模板中,是否有一种优雅的方式来表示逗号分隔的列表,而不使用后面的逗号?

我正在使用 胡子模板库,并尝试生成一个逗号分隔的列表,没有尾随逗号,例如。

红,绿,蓝

考虑到结构,创建一个后跟逗号的列表很简单

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

还有模板

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

这将决定

红色,绿色,蓝色,

然而,如果没有后面的逗号,我就无法找到一种优雅的表达方式。我总是可以在将列表传递到模板之前用代码生成它,但是我想知道库是否提供了一种替代方法,比如允许您检测它是否是模板中列表中的最后一项。

51344 次浏览

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"}
]
}

and your template

\{\{#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.

I think a better way is to change the model dynamically. For example, if you are using JavaScript:

model['items'][ model['items'].length - 1 ].last = true;

and in your template, use inverted section:

\{\{#items}}
\{\{name}}\{\{^last}}, \{\{/last}}
\{\{/items}}

to render that comma.

Interesting. I know it's kind of lazy but I usually get around this by templating in the value assignment rather than trying to comma delimitate the values.

var global.items = {};
\{\{#items}}
global.items.\{\{item_name}} = \{\{item_value}};
\{\{/items}}

The question of whether Mustache offers an elegant way to do this has been answered, but it occurred to me that the most elegant way to do this may be to use CSS rather than changing the model.

Template:

<ul class="csl">\{\{#items}}<li>\{\{name}}</li>\{\{/items}}</ul>

CSS:

.csl li
{
display: inline;
}
.csl li:before
{
content: ", "
}
.csl li:first-child:before
{
content: ""
}

This works in IE8+ and other modern browsers.

Cheat and use CSS.

If your model is:

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

then make your template

<div id="someContainer">
\{\{#items}}
<span>\{\{name}}<span>
\{\{/items}}
</div>

and add a little bit of CSS

#someContainer span:not(:last-of-type)::after {
content: ", "
}

I'm guessing someone will say that this is a bad case of putting markup in the presentation but I don't think it is. Comma separating values is a presentation decision to make interpreting the underlying data easier. It's similar to alternating the font color on entries.

I can't think of many situations where you'd want to list an unknown number of items outside of a <ul> or <ol>, but this is how you'd do it:

<p>
Comma separated list, in sentence form;
\{\{#each test}}\{\{#if @index}}, \{\{/if}}\{\{.}}\{\{/each}};
sentence continued.
</p>

…will produce:

Command separated list, in sentence form; asdf1, asdf2, asdf3; sentence continued.

This is Handlebars, mind you. @index will work if test is an Array.

There is not a built-in way to do this in Mustache. You have to alter your model to support it.

One way to implement this in the template is to use the inverted selection hat \{\{^last}} \{\{/last}} tag. It will only omit text for the last item in the list.

\{\{#items}}
\{\{name}}\{\{^last}}, \{\{/last}}
\{\{/items}}

Or you can add a delimiter string as ", " to the object, or ideally the base class if you're using a language that has inheritance, then set "delimiter" to an empty string " " for the last element like this:

\{\{#items}}
\{\{name}}\{\{delimiter}}
\{\{/items}}

If you happen to be using jmustache, you can use the special -first or -last variables:

\{\{#items}}\{\{name}}\{\{^-last}}, \{\{/-last}}\{\{/items}}

For JSON data I suggest:

Mustache.render(template, settings).replace(/,(?=\s*[}\]])/mig,'');

The regexp will remove any , left hanging after the last properties.

This will also remove , from string values contining ", }" or ", ]" so make sure you know what data will be put into your JSON

As the question is:

is there an elegant way of expressing a comma separated list without the trailing comma?

Then changing the data - when being the last item is already implicit by it being the final item in the array - isn't elegant.

Any mustache templating language that has array indices can do this properly,. ie. without adding anything to the data. This includes handlebars, ractive.js, and other popular mustache implementations.

\{\{# names:index}}
\{\{ . }}\{\{ #if index < names.length - 1 }}, \{\{ /if }}
\{\{ / }}

I tend to think this is a task well suited to CSS (as answered by others). However, assuming you are attempting to do something like produce a CSV file, you would not have HTML and CSS available to you. Also, if you are considering modifying data to do this anyway, this may be a tidier way to do it:

var data = {
"items": [
{"name": "red"},
{"name": "green"},
{"name": "blue"}
]
};


// clone the original data.
// Not strictly necessary, but sometimes its
// useful to preserve the original object
var model = JSON.parse(JSON.stringify(data));


// extract the values into an array and join
// the array with commas as the delimiter
model.items = Object.values(model.items).join(',');


var html = Mustache.render("\{\{items}}", model);

In case using Handlebars is an option, which extends the capabilities of Mustache, you could use a @data variable:

\{\{#if @last}}, \{\{/if}}

More info: http://handlebarsjs.com/reference.html#data

If you are using java, you can use the following :

https://github.com/spullara/mustache.java/blob/master/compiler/src/test/java/com/github/mustachejava/util/DecoratedCollectionTest.java

MustacheFactory mf = new DefaultMustacheFactory();
Mustache test = mf.compile(new StringReader("\{\{#test}}\{\{#first}}[\{\{/first}}\{\{^first}}, \{\{/first}}\"\{\{value}}\"\{\{#last}}]\{\{/last}}\{\{/test}}"), "test");
StringWriter sw = new StringWriter();
test.execute(sw, new Object() {
Collection test = new DecoratedCollection(Arrays.asList("one", "two", "three"));
}).flush();
System.out.println(sw.toString());

Simplest way I found was to render list and then remove last char.

  1. Render mustache.
  2. Remove any white space before and after string.
  3. Then remove last character

    let renderedData = Mustache Render(dataToRender, data); renderedData=(renderedData.trim()).substring(0, renderedData.length-1)

I know this is an old question, but I still wanted to add an answer that provides another approach.

Main answer

Mustache supports lambdas, (see documentation) so one can write it this way:

Template:

    \{\{#removeTrailingComma}}\{\{#items}}\{\{name}}, \{\{/items}}\{\{/removeTrailingComma}}

Hash:

    {
"items": [
{"name": "red"},
{"name": "green"},
{"name": "blue"}
]
"removeTrailingComma": function() {
return function(text, render) {
var original = render(text);
return original.substring(0, original.length - 2);
}
}
}

Output:

red, green, blue

Comment

Personally, I like this approach over the others, since IMHO the model should only specify what is rendered and not how it is rendered. Technically, the lambda is part of the model, but the intent is much more clear.

I use this approach for writing my own OpenApi generators. There, Mustache is wrapped by Java, but the functionality is pretty much the same. This is what creating lambdas looks like for me: (in Kotlin)

    override fun addMustacheLambdas(): ImmutableMap.Builder<String, Mustache.Lambda> =
super.addMustacheLambdas()
.put("lowerCase", Mustache.Lambda { fragment, writer ->
writer.write(fragment.execute().toLowerCase())
})
.put("removeLastComma", Mustache.Lambda { fragment, writer ->
writer.write(fragment.execute().removeSuffix(","))
})
.put("printContext", Mustache.Lambda { fragment, writer ->
val context = fragment.context()
println(context) // very useful for debugging if you are not the author of the model
writer.write(fragment.execute())
})

I'm using custom functions for that, in my case when working with dynamic SQL queries.

    $(document).ready(function () {
var output = $("#output");
var template = $("#test1").html();
var idx = 0;
var rows_count = 0;
var data = {};
    

data.columns = ["name", "lastname", "email"];
data.rows  = [
["John", "Wick", "john.wick@hotmail.com"],
["Donald", "Duck", "donald.duck@ducks.com"],
["Anonymous", "Anonymous","jack.kowalski@gmail.com"]
];


data.rows_lines = function() {
let rows = this.rows;
let rows_new = [];
for (let i = 0; i < rows.length; i++) {
let row = rows[i].map(function(v) {
return `'${v}'`
})
rows_new.push([row.join(",")]);
}
rows_count = rows_new.length;
return rows_new
}


data.last = function() {
return idx++ === rows_count-1; // omit comma for last record
}
    

var html = Mustache.render(template, data);
output.append(html);


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/4.0.1/mustache.min.js"></script>
<h2>Mustache example: Generate SQL query (last item support - omit comma for last insert)</h2>


<div id="output"></div>


<script type="text/html" id="test1">
INSERT INTO Customers(\{\{{columns}}})<br/>
VALUES<br/>
\{\{#rows_lines}}
(\{\{{.}}})\{\{^last}},\{\{/last}}<br/>
\{\{/rows_lines}}
</script>

https://jsfiddle.net/tmdoit/4p5duw70/8/

In more complex scenarios, a view model is desirable for lots of reasons. It represents the model's data in a manner that is better suited for display or, in this case, template processing.

In case you are using a view model, you can easily represent lists in a way that facilitates your goal.

Model:

{
name: "Richard",
numbers: [1, 2, 3]
}

View Model:

{
name: "Richard",
numbers: [
{ first: true, last: false, value: 1 },
{ first: false, last: false, value: 2 },
{ first: false, last: true, value: 3 }
]
}

The second list represention is horrible to type but extremely straightforward to create from code. While mapping your model to the view model, just replace every list you need first and last for with this representation.

function annotatedList(values) {
let result = []
for (let index = 0; index < values.length; ++index) {
result.push({
first: index == 0,
last: index == values.length - 1,
value: values[index]
})
}
return result
}

In case of unbounded lists, you can also only set first and omit last, as one of them is sufficient for avoiding the trailing comma.

Using first:

\{\{#numbers}}\{\{^first}}, \{\{/first}}\{\{value}}\{\{/numbers}}

Using last:

\{\{#numbers}}\{\{value}}\{\{^last}}, \{\{/last}}\{\{/numbers}}

A little late to the party but perhaps helpful for someone looking now: 5.1.1 can do this:

\{\{#allVars}}\{\{name}}\{\{^-last}}, \{\{/-last}}\{\{/allVars}}

Output:

var1, var2, var3

The @LostMekkaSoft solution make sense, but lambda is a problem for simple tasks (helper functions):

Perhaps a solution is a complex helper-function that "inject" this kind of standard lambdas in the input, by additional input-configuration... Another solution is to elect a set of "standard functions" and build it as a Standard Mustache Helper-functions library for each language.

Mustache need a standard helper-library

Suppose a library of ms_*() Mustache helper functions. Example of ms_items_setLast() definition. To implement, the most voted solution here (in 2021) is the @Clyde's solution; so, generalizing it for any language:

For Javascript:

function ms_items_setLast(x,label='') {
if (label=='' || label === undefined)
x[ x.length - 1 ].last = true
else
x[label][ x[label].length - 1 ].last = true
return x
}
// model = ms_items_setLast(model,'items');

For Python:

def ms_items_setLast(x,label=''):
if label=='':
x[ len(x) - 1 ]['last'] = True
else:
x[label][ len(x[label]) - 1 ]['last'] = True

using it at terminal:

model = {
"items": [
{"name": "red"},
{"name": "green"},
{"name": "blue"}
]
}
items= [
{"name": "red"},
{"name": "green"},
{"name": "blue"}
]
ms_items_setLast(model,'items')
ms_items_setLast(items)
model
items

results in

>>> model
{'items': [{'name': 'red'}, {'name': 'green'}, {'name': 'blue', 'last': True}]}
>>> items
[{'name': 'red'}, {'name': 'green'}, {'name': 'blue', 'last': True}]