Nodejs EJS 辅助函数? [英] Nodejs EJS helper functions?

查看:31
本文介绍了Nodejs EJS 辅助函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将辅助函数注册到 EJS 模板,以便可以从任何 EJS 模板调用它们?所以,它应该像这样工作.

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

推荐答案

是的,在 Express 3 中,您可以向 app.locals 添加帮助程序.例如:

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

注意:Express 2.5 对 helper 的处理方式不同.

Note: Express 2.5 did helpers differently.

这篇关于Nodejs EJS 辅助函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆