Nodejs EJS helper functions? Nodejs EJS helper functions? express express

Nodejs EJS helper functions?


Yes, in Express 3 you can add helpers to app.locals. Ex:

app.locals.somevar = "hello world";app.locals.someHelper = function(name) {  return ("hello " + name);}

These would be accessible inside your views like this:

<% somevar %><% someHelper('world') %>

Note: Express 2.5 did helpers differently.


I have another solution to this, and I think it has some advantages:

  • Don't polute your code exporting filters.
  • Access any method without the need to export them all.
  • Better ejs usage (no | pipes).

On your controller:

exports.index = function(req, res) {// send your function to ejs    res.render('index', { sayHi: sayHi });}function sayHi(name) {    return 'Hello ' + name;};

Now you can use sayHi function inside your ejs:

<html>    <h1><%= sayHi('Nice Monkey!') %></h1></html>

You can use this method to send modules to ejs, for example, you could send 'moment' module to format or parse dates.


Here's an example filter...I'm not familiar with helpers.

var ejs = require('ejs');ejs.filters.pluralize = function(num, str){    return num == 1 ? str : str+'s';}; <%=: items.length | pluralize:'Item' %>

Will produce "Item" if it's 1, or if 0 or > 1, produces "Items"

app.js

ejs.filters.sayHi = function(name) {    return 'Hello ' + name;});

index.ejs

<%=: 'Bob' |  sayHi %>