Reputation: 435
I am trying to render an array and apply filtering in EJS.
I would like to loop over the array and sort ascending by name.
The docs do not give much straightforward info about filtering methods
View:
<select>
<% for( var i=0; i < genres.length; i++){ %>
<option value="<%=: genres[i].name | sort_by:'asc' %>"><%= genres[i].name %></option>
<% }; %>
</select>
Service:
var express = require('express'),
ejs = require('ejs');
const genres = [{ name: 'action' }, { name: 'fiction' }, { name: 'thriller' }];
ejs.filters.sort_by = function() {
console.log(genres)
};
Err:
SyntaxError: Unexpected token ':'
Upvotes: 0
Views: 2809
Reputation: 2434
Sorting of an array can be done in plain Javascript inside the EJS template:
<select>
<% genres.sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0)) %>
<% for (const genre of genres) { %>
<option value="<%= genre.name %>"><%= genre.name %></option>
<% } %>
</select>
A thorough explanation of the one-line sorting can be found here.
Upvotes: 0
Reputation: 435
Reading this from https://www.javascripting.com/view/ejs I think this answers my question.
NOTE: Version 2 of EJS makes some breaking changes with this version (notably, removal of the filters feature). Work on v2 is happening here: https://github.com/mde/ejs
https://github.com/mde/ejs/blob/master/docs/syntax.md
Upvotes: 1