user2854314
user2854314

Reputation: 11

How to put objects dynamically in res.render

How can I get an object dynamically in res.render in express in a MEAN stack?

res.render('myTemplate', {title: 'This is my title'});

I want something like this:

res.render('myTemplate', function(){
    var myReturnObject{title: 'This is my title'};
    //do someting to generate return object;
    return myReturnObject;
});

Can anyone advise how can I generate my template variables programmatically in render function?

Thanks.

Upvotes: 1

Views: 877

Answers (2)

Julien Klepatch
Julien Klepatch

Reputation: 348

Your res.render() calls will live in the context of a controller. For example , it could be something like (app.get('/', function(req, res) {});. Typically, you would want to fetch some data, then pass the fetched data to the template in your res.render() callback. The snippet below show how you would do this with a fictitious callToDb() function that query a database:

app.get('/', function(req, res) {
  callToDB(function(err, results) {
    const templateVars = {//use results like you want here};
    res.render('path/to/template/, templateVars);
  });
});

Upvotes: 0

Mark S.
Mark S.

Reputation: 4017

You can put your data into an object and then pass it in the res.render.

var myReturnObject = {title: 'This is my title'};
res.render('myTemplate', myReturnObject);

Upvotes: 1

Related Questions