Nodejs EJS helper functions?

匿名 (未验证) 提交于 2019-12-03 02:46:02

问题:

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

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



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