Render template to variable in expressjs

前端 未结 3 688
耶瑟儿~
耶瑟儿~ 2020-12-16 13:40

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

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

something like this

相关标签:
3条回答
  • 2020-12-16 14:28

    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.

    0 讨论(0)
  • 2020-12-16 14:34

    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.

    0 讨论(0)
  • 2020-12-16 14:37

    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.

    0 讨论(0)
提交回复
热议问题