一旦我在Express中设置了一个全局变量
app.use(function(req, res, next){
res.locals.isAuthenticated = true;
next();
});
Run Code Online (Sandbox Code Playgroud)
如何从任何视图(*.marko模板)中获取该变量?
我知道在Jade你应该可以像任何其他变量一样直接访问它,而不需要将它从子模板传递给父模板.Marko JS中的等价物是什么?
谢谢
小智 7
使用Marko,您通常希望绕过Express视图引擎并将模板直接呈现给可写res流:
var template = require('./template.marko');
app.use(function(req, res){
var templateData = { ... };
template.render(templateData, res);
});
Run Code Online (Sandbox Code Playgroud)
使用该方法,您可以完全控制传递给模板的数据.从技术上讲,您可以res.locals通过执行以下操作访问模板:
<div if="out.stream.locals.isAuthenticated">
Run Code Online (Sandbox Code Playgroud)
注意:out.stream只是对正在写入的可写流的引用(在本例中res)
您还有其他选择:
使用res.locals模板数据
var template = require('./template.marko');
app.use(function(req, res){
var templateData = res.locals;
template.render(templateData, res);
});
Run Code Online (Sandbox Code Playgroud)
从中构建模板数据 res.locals
var template = require('./template.marko');
app.use(function(req, res){
var templateData = {
isAuthenticated: res.locals.isAuthenticated
};
template.render(templateData, res);
});
Run Code Online (Sandbox Code Playgroud)
Marko还支持可使用的"全局"数据out.global.请参阅:http://markojs.com/docs/marko/language-guide/#global-properties
如果您还有疑问,请分享!
| 归档时间: |
|
| 查看次数: |
879 次 |
| 最近记录: |