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

后端 未结 17 1603
滥情空心
滥情空心 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:57

    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);
    

提交回复
热议问题