Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render template to variable in expressjs

Is there a way to render template to a variable instead to output?

res.render('list.ejs', {
    posts: posts
});

something like this

var list = render('list.ejs', {
    posts: posts
});
like image 319
xrado Avatar asked Oct 02 '11 08:10

xrado


3 Answers

The easiest way to do that is to pass a callback to res.render, in your example:

res.render('list.ejs', {posts: posts}, function(err, list){
  // 
});

But if you want to render partial templates in order to include them in another template you definitely should have a look at view partials.

like image 176
Adrien Avatar answered Nov 04 '22 04:11

Adrien


I am quite a newbie on express.js, anyway I am not sure you can access the rendered string that way, although if you look at express' "view.js" source on github (here) you see that it's accepting a callback as second argument, if that may help: you may access the rendered string there.

Otherwise, I think it's quite easy to patch the code to add a method returning the rendered string without sending it: on line #399 you have the very call that gives the string you are looking for.

like image 40
Savino Sguera Avatar answered Nov 04 '22 06:11

Savino Sguera


This wasn't the question originally asked, but based on comments from the OP and others, it seems like the goal is to render a partial via json (jsonp), which is something I just had to do.

It's pretty easy:

app.get('/header', function (req, res)
{
    res.render('partials/header', { session: req.session, layout: null }, function (err, output)
    {
        res.jsonp({ html: output });
    });    
});

Note: In my case, the header partial required the session, and my template library (express-hbs) needed layout: null to render the partial without using the default layout.

You can then call this from Javascript code in the client like any other JSONP endpoint.

like image 2
BobDickinson Avatar answered Nov 04 '22 04:11

BobDickinson