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

Nodejs EJS helper functions?

Nodejs EJS helper functions?

Problem

Is there a way to register Helper Functions to EJS templates, so that they can be called from any EJS template? So, it should work something like this.

app.js

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

index.ejs


Problem courtesy of: Stephen Bugs Kamenar

Solution

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:




Note: Express 2.5 did helpers differently.

Solution courtesy of: dylanized

Discussion

View additional discussion.



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

Share the post

Nodejs EJS helper functions?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×