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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With