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

后端 未结 17 1618
滥情空心
滥情空心 2020-12-02 10:26

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

red, green, blue

17条回答
  •  情歌与酒
    2020-12-02 10:56

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

提交回复
热议问题