dylanized
dylanized

Reputation: 3855

Inside Express/EJS templates, what is cleanest way to loop through an array?

I have an Express.js app set up using EJS templates. I successfully looped through an array with classic JS syntax:

<% for (var i = 0; i < myArray.length; i++) { 
    this = myArray[i];
    // display properties of this
} %>

But I'm wondering, is there a cleaner way to do this?

Specifically, can I use Underscore or Lodash to loop through with .each ? thank you

Upvotes: 28

Views: 33831

Answers (2)

Julian
Julian

Reputation: 4366

@wachme's answer is correct, but to stick with the original question, here is the version using Underscore's _.each (and integrated in template syntax):

<% _.each(myArray, function(el, index) { %>
    Value is <%= el %>, index is <%= index %>.
<% }) %>

The advantage of Array.prototype.forEach is that you don't need to depend on Underscore in your templates. The advantage of _.each is that it has some additional tricks up its sleeves (for example, it also works on objects) and that it works in older JS environments without any need for polyfills.

As an aside, Underscore's _.template can be used instead of EJS, although it has fewer features. Also, the meaning of <%= and <%− is swapped between the two libraries. Naturally, you can always use _.each in Underscore templates.

Upvotes: 0

wachme
wachme

Reputation: 2337

You can use forEach method

myArray.forEach(function(el, index) {
    // el - current element, i - index
});

Upvotes: 71

Related Questions