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});
Author by
kulebyashik
Updated on June 12, 2022Comments
-
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 about 13 yearsare 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 about 13 yearsThen what you want is not really "express" but just plain old ajax.
-
Raynos about 13 yearsI have functionality similar to this explained in my blog post about re-using views on the client
-
-
uKolka about 13 yearsAny reason you chose
req.isXMLHttpRequest
over the aliasedreq.xhr
;) -
Peter Lyons about 13 yearsit'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 over 11 yearsFor me
req.isXMLHttpRequest
returns undefined, using express 3.x, any guesses why? -
Peter Lyons over 11 yearsIn express 3.x it's just req.xhr
-
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