Render template to variable in expressjs

前端 未结 3 703
耶瑟儿~
耶瑟儿~ 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: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.

提交回复
热议问题