Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 952
topskip Avatar asked Jan 05 '12 19:01

topskip


People also ask

How do I make .EJS variables accessible to JS files?

It is possible to access JS variable in . ejs file. You just need to pass the JS object as second parameter of res. render() method.

How do I open an EJS file?

If you cannot open your EJS file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a EJS file directly in the browser: Just drag the file onto this browser window and drop it.


1 Answers

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 <%=: data_to_be_filtered | your_filter %>.

Example application:

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 in /views)

<%=: data | my_custom_filter %>

Download the code directly from github: http://github.com/alessioalex/ejs_filters

Fore more information checkout: https://github.com/visionmedia/ejs

like image 75
alessioalex Avatar answered Oct 04 '22 15:10

alessioalex