可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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