0

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 ':'
timber535
  • 425
  • 1
  • 3
  • 17
  • 1
    Hi, please remove ":" (before genres there's an colon) in this line. – KonohaNinja May 12 '21 at 16:33
  • Just to clarify the colon is part of the EJS filtering syntax which I would like to get working. The error log is not the issue just a confirmation that the implementation isn't correct – timber535 May 12 '21 at 19:56
  • 1
    Filters haven't been an EJS feature since the original implementation. Either sort `genres` prior to hitting the view layer, or sort before iterating. [REF](https://github.com/mde/ejs/issues/505) – Dave Newton May 13 '21 at 14:19

2 Answers2

1

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

timber535
  • 425
  • 1
  • 3
  • 17
0

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.

Lucio Mollinedo
  • 2,295
  • 1
  • 33
  • 28