Nodejs EJS helper functions?

后端 未结 4 1564
一个人的身影
一个人的身影 2020-12-08 04:46

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

<
4条回答
  •  猫巷女王i
    2020-12-08 05:06

    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:

    
        

    <%= sayHi('Nice Monkey!') %>

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

提交回复
热议问题