Once I set a global variable in Express using
app.use(function(req, res, next){
res.locals.isAuthenticated = true;
next();
});
How can I get that variable from inside any view (*.marko template)?
I know in Jade you should be able to access it directly like any other variable, without the need to pass it from child to parent template. What's the equivalent in Marko JS?
Thanks
With Marko you typically want to bypass the Express view engine and render a template directly to the writable res stream:
var template = require('./template.marko');
app.use(function(req, res){
var templateData = { ... };
template.render(templateData, res);
});
With that approach you have full control over what data is passed to your template. Technically, you have access to res.locals in your template by doing the following:
<div if="out.stream.locals.isAuthenticated">
NOTE: out.stream is simply a reference to the writable stream that is being written to (in this case, res)
You have some other options:
Use res.locals as template data
var template = require('./template.marko');
app.use(function(req, res){
var templateData = res.locals;
template.render(templateData, res);
});
Build template data from res.locals
var template = require('./template.marko');
app.use(function(req, res){
var templateData = {
isAuthenticated: res.locals.isAuthenticated
};
template.render(templateData, res);
});
Marko also supports "global" data that is accessible using out.global. See: http://markojs.com/docs/marko/language-guide/#global-properties
If you still have questions then please share!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With