node.js Express - How to get partial views asynchronously

12,447

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});
Share:
12,447
kulebyashik
Author by

kulebyashik

Updated on June 12, 2022

Comments

  • kulebyashik
    kulebyashik about 2 years

    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.

    • jcolebrand
      jcolebrand about 13 years
      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
      jcolebrand about 13 years
      Then what you want is not really "express" but just plain old ajax.
    • Raynos
      Raynos about 13 years
      I have functionality similar to this explained in my blog post about re-using views on the client
  • uKolka
    uKolka about 13 years
    Any reason you chose req.isXMLHttpRequest over the aliased req.xhr ;)
  • Peter Lyons
    Peter Lyons about 13 years
    it's just a clearer name. I generally prefer code that's easier to read over code that's easier to write if I have the option.
  • Amol M Kulkarni
    Amol M Kulkarni over 11 years
    For me req.isXMLHttpRequest returns undefined, using express 3.x, any guesses why?
  • Peter Lyons
    Peter Lyons over 11 years
    In express 3.x it's just req.xhr
  • Victor Schröder
    Victor Schröder about 10 years
    res.partial() is now deprecated and removed from Express 3.x. They recommend to use blocks: github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.‌​x