I am Hack Sparrow
Captain of the Internets.

Express.js Jade Partials – How to use them

What are Partials and how do you use them in Express?


Partials are mini views that can be rendered in a HTTP response. They are mainly used for modularizing the view of an HTTP response. Since Jade is the default HTML template engine, this post explains what partials are in Express assuming we are talking about Jade partials for Express.js.

Partials are regular Jade templates that caters to specific part of a larger view. For example, if you want to break up the view of a page of videos, you might do something like this:

File: videos.jade

- each video in videos
!=partial('partials/video', {title:video.title, artist:video.artist})

File: partials/video.jade

.video #{title} by #{artist}

The usefulness of partials may not be very obvious in the above example, but you can guess their importance in more complicated use-cases. Also note, you need not keep your partials in a directory named partials, keep it anywhere, just point to it right.

There are two ways of using partials in Express - i. In Express using res.partial(), ii. In Jade using !=partial(). If you are familiar with res.render() using Jade, you already know how to use partials. Their syntax look like this:

In Express

res.partial(template name[, options]);

In Jade

!=partial(template name[, options])

where template name and options are exactly what you pass to res.render().

Wondering what's the difference between res.render() and res.partials()?

res.render() is used to send a whole HTML page, code>res.partials() is used for sending HTML snippets (mainly as Ajax response). You could use res.render() to send HTML snippets too by setting the layout option to false, but why create confusion? It's best to maintain the distinction - res.render() for HTML pages, res.partial() for HTML snippets.

And ... what is the difference between include and partial in Jade?

You cannot pass objects to include templates, you can pass objects to partial templates. Use includes for non-dynamic views, partials for dynamic views. If you are familiar with Flash, partials are best used as ItemRenderers.

So that's pretty much about partials in Express.js. I hope you understood how partials work in Express now. Any questions, remarks, need more examples? Ping me in the comments.

13 Responses to “Express.js Jade Partials – How to use them”

  1. Ian Morton says:

    Using includes, instead of partials, but I’m having a problem passing through an object eg {title:video.title, artist:video.artist} . Is that possible?

  2. Captain says:

    Yes, very much possible.

    “A Jade view file and its included Jade files share the same scope. So variables defined in one file are available to the other.” – from my book, Express Web Application Development – http://expressjs-book.com.

  3. jorawebdev says:

    Thank you! The best explanation I found.

Make a Comment