Nodejs EJS helper functions?

后端 未结 4 1549
一个人的身影
一个人的身影 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条回答
  • 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:

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

    0 讨论(0)
  • 2020-12-08 05:09

    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

    0 讨论(0)
  • 2020-12-08 05:10

    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.

    0 讨论(0)
  • 2020-12-08 05:25

    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 %>
    
    0 讨论(0)
提交回复
热议问题