Cyril N.
Cyril N.

Reputation: 39869

Loop over and array and add a separator except for the last

Using Handlebarjs, I'd like to loop over an array, and display values, separated by a separator. It would be easy if the content I want to display wasn't a template too ;)

Here's my case :

accounts = [
     {'name': 'John', 'email': '[email protected]'},
     {'name': 'Malcolm', 'email': '[email protected]'},
     {'name': 'David', 'email': '[email protected]'}
];

{{#each accounts}}
    <a href="mailto:{{ email }}" title="Send an email to {{ name }}">{{ name }}</a>,
{{/each}}

The problem with this implementation is that I will have this output :

John, Malcolm, David,

And I'd like it to be :

John, Malcolm, David

How can I do that ?

Upvotes: 0

Views: 917

Answers (2)

Cyril N.
Cyril N.

Reputation: 39869

I implemented a new foreach helper that can do the trick :

Handlebars.registerHelper('foreach', function (array, fn) {
    var total = array.length;
    var buffer = '';

    //Better performance: http://jsperf.com/for-vs-foreach/2
    for (var i = 0, j = total; i < j; i++) {
        var item = array[i];

        // stick an index property onto the item, starting with 1, may make configurable later
        item['_index'] = i+1;
        item['_total'] = total;
        item['_isFirst'] = (i === 0);
        item['_isLast'] = (i === (total - 1));

        // show the inside of the block
        buffer += fn.fn(item);
    }

    // return the finished buffer
    return buffer;
});

And then :

{{#foreach accounts}}
    <a href="mailto:{{ email }}" title="Send an email to {{ name }}">{{ name }}</a>{{#unless _isLast}}, {{/unless}}
{{/foreach}}

Upvotes: 2

joholo
joholo

Reputation: 633

You can use CSS pseudo class :after, together with content, to achieve the required "formatting". (:after and content support in most browser today, and IE8+.)

For example:

HTML:

<a href="mailto:[email protected]" title="Send an email to Foo">Foo1</a>
<a href="mailto:[email protected]" title="Send an email to Foo">Foo2</a>
<a href="mailto:[email protected]" title="Send an email to Foo">Foo3</a>

CSS:

a {
  color: red;
}
a:after {
  content: ", ";
}
a:last-child:after {
  content: "";
}

Result:

Foo1, Foo2, Foo3

Upvotes: 3

Related Questions