Add incrememter to id in ejs

4.2k views Asked by At

I am working on a javascript page that uses an MVC format and canJS. In my view property when I add new elements I want to add id's and dynamically assign new ids to each thing I load.

The code in my .ejs file is somehting like this:

<ul>
<% can.each(pages, function(val, key){ %>
<li id="<% 'page' + // Add incrementer here%>"><%= val.attr('Title') %>
</li>
</ul>

Where pages is iterable. I want to add an incrementer so every page I add has a unique id for reference later. Is this possible in the .ejs file?

Thanks

2

There are 2 answers

0
Hannes Obweger On BEST ANSWER

If the iterable provided to can.each is an array, the callback function of can.each receives the current element's index as its second parameter. This should be perfectly usable as an identifier.

See http://canjs.com/docs/can.each.html

0
matth On

EJS is simply embedded javascript. You can use loop through the array pages using forEach, and the key variable would increment with every page (basically what Hannes Obweger suggested).

<ul>
    <% pages.forEach(function(val, key) { %>
        <li id="page_<%= key %>"><%= val.Title %></li>
    <% }); %>
</ul>