3

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

crash
  • 4,152
  • 6
  • 33
  • 54

1 Answers1

7

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!

  • Thanks @Patrick Steele-Idem, the only thing I had to do apart from the code I wrote on my post was to check the variable with `if="out.stream.locals.isAuthenticated"` as you said. Nothing more! This way I don't have to pass the variable directly to the template as the other examples you suggested. What about `app.locals` ? How can I reach those? – crash Jan 13 '16 at 10:27
  • Hey @crash, the `app` instance hangs off of `res` and `req` as `res.app` and `req.app`, respectively, so you can access `app.locals` as `out.stream.app.locals`. – Patrick Steele-Idem Jan 13 '16 at 15:10
  • For people like me who arrived here and found a dead link : we can access req, res, app, app.locals, and res.locals automatically by out.global in any view by using res.marko instead of template.render with express. See https://markojs.com/docs/express/#usage – ElJackiste Mar 06 '18 at 11:13