您好,我想知道是否有将变量或对象传递给布局 View 的正确方法?
这就是我目前正在做的并且有效
index: function(req, res){
res.view({ layout: 'mylayout', myvar: 'This is a view var' });
}
但是我必须在每个 Action 上定义“myvar”,这样我才能在布局级别使用它,所以我想知道是否有某种类型的布局 Controller 或 Action ,以便我可以将我的逻辑放在那里?
最佳答案
实际上从 Sails v0.10-rc5 开始,您可以使用 sails.config.views.locals
哈希来指定默认情况下应提供给所有 View 的变量。所以在 config/views.js
中,像这样:
{
locals: {
myvar : 'this is a view var'
}
}
会将 var 添加到每个 View 。这对于影响 View 引擎的变量非常有用;见here了解更多详情。
您还可以使用 policy在 Sails v0.10.x 中,通过更改 req.options.locals
跨多个 View 设置变量。因此,如果您使用以下内容创建了一个策略 /api/policies/decorate.js
:
module.exports = function(req, res, next) {
// Default to an object if empty, or use existing locals that may have
// been set elsewhere
req.options.locals = req.options.locals || {};
// Set a new local var that will be available to any controller that
// implements the policy
req.options.locals.myVar = Math.random()
然后设置你的 /config/policies.js
像这样:
module.exports = {
'*': 'decorate'
}
然后任何使用 res.view
的 Controller 操作都会在 View 中提供该 myVar
变量。
关于javascript - SailsJS 将对象/变量传递给布局 View 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23090659/