3

Possible Duplicate:
How do I add a separator between elements in an {{#each}} loop except after the last element?

As a simplest case, lets say that I have a list of names and I want them to be displayed with commas between them. I could do

{{#each name in names }} {{name}}, {{/each}}

which would then produce the last

John, Paul, George, Ringo,

with a final comma that is not wanted. I can think of ways to handle this by adding the commas in my controller functions, but that seems awkward and kind of infringes on the MVC separation. Is there a way just in handlebars to identify when you're dealing with the last element and adjust accordingly?

Community
  • 1
  • 1
BostonJohn
  • 2,631
  • 2
  • 26
  • 48

2 Answers2

1

Javascript has a .join function which you most probably can use:

['John', 'Paul', 'George', 'Ringo'].join(', '); //John, Paul, George, Ringo
Naftali
  • 144,921
  • 39
  • 244
  • 303
0

Another way in case you are not able to use Join.

var arr = ['John', 'Paul', 'George', 'Ringo'];
var names="";
$.each(arr, function(i,val) { 

if (i < arr.length-1)
  names += val + ","
else
 names += val
 });
alert (names);
DJ.
  • 528
  • 7
  • 16