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

11

我想在jade模板中使用下划线函数,就像这样:

p= _.keys(user)

这并不适用于客户端JavaScript,而是在渲染中使用。

虽然我在app.js中引入了'underscore',但并不顺利。当然,在app.js中它可以正常工作。

ReferenceError: xxxxxxx _ is not defined

这是模板错误信息。 有什么想法吗?

谢谢。

2个回答

20

如果您正在使用Express.js(假设您正在使用Jade),则可以将underscore添加为view helper

app.helpers({
    _: require("underscore")
});

更新 使用 Express 3+,以上方法将不再适用,请改用app.locals:

app.locals._ = require("underscore");

超级棒的答案。为我解决了3个问题!谢谢。 - Codious-JR

5
在 Express 3.x 版本中,助手(helpers)被移除了。取而代之的是使用中间件(middleware)和 res.locals
app.use(function(req, res, next){
  res.locals._ = require('underscore');
  next();
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接