node.js Express - How to get partial views asynchr

2019-03-17 02:24发布

I've got a layout - navigation menu. In express tutorials theres only old-school pages loading. whole old page is thrown away and a new one is downloaded with all layouts,views and partial views. And i want navigation menu to stay. So how can i do that?

If i'm maybe getting smth wrong with this web pages architecture please guide me.

2条回答
smile是对你的礼貌
2楼-- · 2019-03-17 03:03

As @drachenstern said, you want to render only partial HTML fragments, not whole documents including the layout. You can tell express to skip the layout using:

res.render('sometemplate', {layout: false});

If you want to look for Ajax requests as distinct from full-page browser loads, use the req.xhr flag as documented here

Thus you might even be able to do

res.render('sometemplate', {layout: !req.xhr});
查看更多
爷的心禁止访问
3楼-- · 2019-03-17 03:16

You can also use res.partial() which is specifically for rendering partials.

Here is a sample of its usage, where 'browse.jade' is name of the template:

exports.browse = function(req, res){
  var Contact = mongoose.model('Contact');
  Contact.where({}).asc('surname', 'given_name', 'org').run(function(err, results) {
    res.partial('browse', { 
        locals: { data: results }
    });
  });
};
查看更多
登录 后发表回答