Nodejs EJS helper functions?

不问归期 提交于 2019-12-18 10:33:23

问题


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') %>

回答1:


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.




回答2:


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.




回答3:


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 %>



回答4:


I am using:

In helpers/helper.js

var func = {
    sayhi: function(name) {
        return "Hello " + name;
    }, 
    foo: function(date) {
        //do somethings
    }    
};
module.exports = func;

In router:

router.get('/', function(req, res, next) {
    res.render('home/index', {
        helper: require('../helpers/helper'),
        title: 'Express'
    });
});

In template:

<%= helper.sayhi("Dung Vu") %>

goodluck



来源:https://stackoverflow.com/questions/13221760/nodejs-ejs-helper-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!