Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable in Marko JS Template and Express

Tags:

node.js

marko

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

like image 249
crash Avatar asked Dec 14 '25 05:12

crash


1 Answers

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!

like image 55
Patrick Steele-Idem Avatar answered Dec 15 '25 19:12

Patrick Steele-Idem