最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Concat with gluejoin using Mustache JS - Stack Overflow

programmeradmin1浏览0评论

I'm trying to display an array of items with Mustache, and I'd like to show them with a ma separator.

Here is my object :

{"items": [
    {"display": "Item 1"},
    {"display": "Item 2"},
    {"display": "Item 3"},
    {"display": "Item 4"}
]}

And here's my Mustache JS template :

{{#items}}{{display}}, {{/items}}

Unfortunately, this will render as :

Item 1, Item 2, Item 3, Item 4, 

I'd like to remove the last ", ", since it seems odd visually.

I tried with functions, but I got the "{{items}}" text, not the array items.

How can I do this?

I'm trying to display an array of items with Mustache, and I'd like to show them with a ma separator.

Here is my object :

{"items": [
    {"display": "Item 1"},
    {"display": "Item 2"},
    {"display": "Item 3"},
    {"display": "Item 4"}
]}

And here's my Mustache JS template :

{{#items}}{{display}}, {{/items}}

Unfortunately, this will render as :

Item 1, Item 2, Item 3, Item 4, 

I'd like to remove the last ", ", since it seems odd visually.

I tried with functions, but I got the "{{items}}" text, not the array items.

How can I do this?

Share Improve this question edited Jan 12, 2020 at 23:19 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Oct 11, 2012 at 10:26 Cyril N.Cyril N. 39.9k40 gold badges163 silver badges268 bronze badges 1
  • I posted a similar question with my own proposed answer. See this posting for more – Michael M Commented Mar 5, 2014 at 22:10
Add a ment  | 

2 Answers 2

Reset to default 6

You could use a Mustache function. These are defined in your template like any other section, then run on the content they're wrapped around. For your case it would look something like this:

{
  "items": [
    {"display": "Item 1"},
    {"display": "Item 2"},
    {"display": "Item 3"},
    {"display": "Item 4"}
  ],
  "trim": function () {
    return function (text, render) {
      return render(text).replace(/(,\s*$)/g, ''); // trim trailing ma and whitespace 
    }
  }
}

Then your Mustache markup will look like this:

{{#trim}}{{#items}}{{display}}, {{/items}}{{/trim}}

And your output will be what you're after:

Item 1, Item 2, Item 3, Item 4

Check it out on jsfiddle.

well i know 2 ways of solve this, first is to program your own iterator helper (and this is the best solution), and the sencond, is to delete manually (with DOM Handling) the trailing a.

just find the text with your javascript ($("selector").html()), and slice it.

var html = jQuery("selector").html();
html = html.slice(0, html.length-1);

that way you cut the last character.

发布评论

评论列表(0)

  1. 暂无评论