node.js - ExpressJS View 中的变量

标签 node.js express

我想让 session 变量(或任何其他变量)在 View 中可用,而无需再次重复。

我想出了这个:

  res.render('index', viewVariables(req, res, params, {});

以及viewVariables函数:

function viewVariables(req, res, params, options) {
  var returnObject = options || {locals:{}};
  var locals = {
    currentUser: req.currentUser ? req.currentUser : false
  };
  returnObject.locals = mergeObjects(locals, returnObject.locals, true);
  return returnObject;
};

这在最新的expressjs版本中不起作用(不同的渲染方法)。

是否有更简单或更优雅的解决方案? (我确信有!)

最佳答案

你看过动态助手吗?

来自网站:

app.dynamicHelpers(obj)

Registers dynamic view helpers. Dynamic view helpers are simply functions which accept req, res, and are evaluated against the Server instance before a view is rendered. The return value of this function becomes the local variable it is associated with.

app.dynamicHelpers({
  session: function(req, res){
    return req.session;
  }
});

大多数时候我喜欢把它变成一个函数。这样,只有当您在 View 中调用该函数时才会调用它。

关于node.js - ExpressJS View 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5245117/

相关文章:

javascript - Node.JS - Sharp 的 overrideWith() 函数的 SVG 到图像缓冲区?

javascript - 正则表达式奇怪地不起作用

node.js - NodeJS 聊天室对象预期第一行

node.js - 帖子参数无法从 postman + Node js获取

javascript - 从 gulp 中启动一个快速服务器

node.js - 咕噜声 : Compile pages in multiple languages (Translation)

node.js - 在 NodeJS 中查找 GeoJSON 点位于哪个多边形

node.js - 运行 Angular 项目会出现 Node-sass 错误

javascript - 类型错误 : Cannot read property 'express-validator#contexts' of undefined

node.js - Node 'extends layout'不显示 block 内容