Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to access the ejs object in express.js

How to access the ejs object in express.js


I am using express (web framework for node.js) with ejs. Now I'd 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];

The question: how do I access that ejs object? I have tried (naively) in app.js:

ejs.filters.myfilter = function (obj) {

which gives me the error:

ReferenceError: ejs is not defined
Problem courtesy of: topskip


You need to require ejs in your application and set a custom filter on it, which will be visible for your Express application. Also note how you use a ejs filter in your view .

Example application:


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] });

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

index.ejs (located in /views)

Download the code directly from github:

Fore more information checkout:

Solution courtesy of: alessioalex


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to access the ejs object in express.js


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription