5

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.

kulebyashik
  • 5,359
  • 4
  • 18
  • 13
  • are you saying that you want the page partial to be like the new google search page, where only part of the page is loaded on the fly? – jcolebrand May 15 '11 at 05:49
  • Then what you want is not really "express" but just plain old ajax. – jcolebrand May 15 '11 at 16:40
  • I have functionality similar to this explained in [my blog post about re-using views on the client](http://gamewithnodejs.blogspot.com/2011/04/setting-up-simple-blog-part-1.html) – Raynos May 19 '11 at 21:07

2 Answers2

12

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});
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
0

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 }
    });
  });
};
Benjen
  • 2,835
  • 5
  • 28
  • 42
  • 1
    `res.partial()` is now deprecated and removed from Express 3.x. They recommend to use blocks: https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x – Victor Schröder Jun 16 '14 at 21:22