How to access an ejs element in express.js

I am using express (web framework for node.js) with ejs. Now I would like to create my own filter, as described on the ejs github page :

To add a filter simply add a method to the .filters object:

ejs.filters.last = function(obj) {
  return obj[obj.length - 1];
};

Question: how to access this element ejs? I tried (naively) in app.js:

ejs.filters.myfilter = function (obj) {
  ....
}

which gives me an error:

ReferenceError: ejs is not defined
+5
source share
1 answer

You need to require ejs in your application and set a custom filter on it that will be displayed for your Express application. Also notice how you use the ejs filter in your view <%=: data_to_be_filtered | your_filter %>.

Application example:

app.js

var app, express = require('express'), ejs = require('ejs');

ejs.filters.my_custom_filter = function(ary) {
  return ary[ary.length - 1];
};

app = express.createServer();

app.configure(function() {
  app.set('view options', { layout: false });
  app.set('view engine', 'ejs');
});

app.get('/', function(req, res) {
  res.render('index', { data: [1, 2, 3, 4, 5] });
});

app.listen(8080);
console.log('Server started on port 8080');

index.ejs (located at / views)

<%=: data | my_custom_filter %>

github: http://github.com/alessioalex/ejs_filters

: https://github.com/visionmedia/ejs

+10

All Articles