一旦我在Express中设置了一个全局变量,使用
app.use(function(req, res, next){
res.locals.isAuthenticated = true;
next();
});如何从任何视图(*.marko模板)中获取该变量?
我知道在Jade中,您应该能够像任何其他变量一样直接访问它,而不需要将它从子模板传递到父模板。在Marko JS中什么是等价物?
谢谢
发布于 2016-01-12 23:54:48
使用Marko,您通常希望绕过Express视图引擎并将模板直接呈现给可写的res流:
var template = require('./template.marko');
app.use(function(req, res){
var templateData = { ... };
template.render(templateData, res);
});通过这种方法,您可以完全控制传递给模板的数据。从技术上讲,您可以通过以下操作访问模板中的res.locals:
<div if="out.stream.locals.isAuthenticated">注意:out.stream只是对被写入的可写流的引用(在本例中是res)。
你还有其他选择:
使用作为模板数据
var template = require('./template.marko');
app.use(function(req, res){
var templateData = res.locals;
template.render(templateData, res);
});从res.locals 构建模板数据
var template = require('./template.marko');
app.use(function(req, res){
var templateData = {
isAuthenticated: res.locals.isAuthenticated
};
template.render(templateData, res);
});Marko还支持使用out.global访问的“全局”数据。请参阅:http://markojs.com/docs/marko/language-guide/#global-properties
如果你还有问题,请分享!
https://stackoverflow.com/questions/34751226
复制相似问题