Skip to content

Partials

Timothy Kempf edited this page Oct 11, 2013 · 12 revisions

A partial is a Handlebars view that is included inside pages, layouts, or even other partials. Partials are generally used encapsulate markup that is used across a number of pages, or simply to "clean up" complex markup by moving portions to their own files.

======

Creating a Partial

Technically, any *.hbs file inside of /views can be used as a partial. This is useful in cases when you want a standalone page that can also be included within other pages as a partial. Partials don't require any special bits like pages or layouts, just markup.

Partials are included in your views by using {{> path/to/partial}}. Say you have the following file structure:

/views
├── index.hbs
├── layout.hbs
└── header.hbs

If you want to include header.hbs as a partial in layout.hbs, just do this in layout.hbs:

<!DOCTYPE html>
<html>
    ...
        <!-- Header -->
        {{> header }}
    ...
</html>

This will render the contents of header.hbs inside of layout.hbs where you place {{> header }}, using the full context of the page.

======

Passing a Context to a Page

Sometimes, you won't want to pass the entire page context to your partial, but instead a specific part of it. In order to pass a portion of the context to your partial, just specify it as the second argument when you include the partial:

<!DOCTYPE html>
<html>
    ...
        <!-- Header -->
        {{> header page }}
    ...
</html>

This will make the partial use only the contents of the page portion of the context, rather than the entire thing.