Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs EJS helper functions?

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

<%= sayHi('Bob') %> 
like image 391
Farzher Avatar asked Nov 04 '12 18:11

Farzher


People also ask

What is helper in node JS?

The node helper ( node_helper. js ) is a Node. js script that is able to do some backend task to support your module. For every module type, only one node helper instance will be created. For example: if your MagicMirror uses two calendar modules, there will be only one calendar node helper instantiated.

What are helper functions in JavaScript?

Helper functions are JavaScript functions that you can call from your template. Ember's template syntax limits what you can express to keep the structure of your application clear at a glance. When you need to compute something using JavaScript, you can use helper functions.

What is helper function?

A "helper function" is a function you write because you need that particular functionality in multiple places, and because it makes the code more readable. A good example is an average function. You'd write a function named avg or similar, that takes in a list of numbers, and returns the average value from that list.


1 Answers

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.

like image 75
dylanized Avatar answered Sep 22 '22 22:09

dylanized