如何在玉模板中使用下划线

dot*_*dot 11 node.js underscore.js pug

我想在jade模板中使用下划线功能,就像这样

p= _.keys(user)
Run Code Online (Sandbox Code Playgroud)

不适用于客户端javascript,适用于redering.

通过我在app.js中确实需要'下划线',并没有很好地相处.当然它在app.js中正常工作.

ReferenceError: xxxxxxx _ is not defined
Run Code Online (Sandbox Code Playgroud)

这是模板错误消息.任何的想法?

谢谢

Dom*_*nes 20

如果您正在使用Express.js(可能是因为您使用的是Jade),您可以添加下划线作为视图助手.

app.helpers({
    _: require("underscore")
});
Run Code Online (Sandbox Code Playgroud)

更新使用Express 3+,以上将不再有效,请app.locals改用:

app.locals._ = require("underscore");
Run Code Online (Sandbox Code Playgroud)


Dav*_*sen 5

在Express 3.x中,删除了帮助程序.而是使用中间件和res.locals

app.use(function(req, res, next){
  res.locals._ = require('underscore');
  next();
});
Run Code Online (Sandbox Code Playgroud)