Question

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

Was it helpful?

Solution 2

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

OTHER TIPS

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top