by Before Semicolon

Partials and Include

Partials are simply a way to split your templates into parts that can be reused in different templates.

Create Partials

To create a partial files all you have to do is create an HTML file which the name starts with an underscore.

# File Structure               # Routes

- server.js
- pages
	- index.html                 /
	- contact.html               /contact
	- about.html                 /about
	- 404.html                   /404
	- partials
		- _header.html
	- projects
		- index.html               /projects
		- todo-project.html        /projects/todo-project

Partial files are ignored by the routes and can only be included in a page templates.

Include partials

To include a partial in your page template you must use the include tag.

<!-- _header.html -->
	<p class="description">Welcome to the projects page</p>

The include tag takes the name of the partial file (without underscore and extension) as the value of the partial attribute and will include the partial file content in your template.

<!-- project.html -->
<include partial="header"></include>

This means that partial file names must be unique and they can be placed anywhere inside your pages directory.

You can also use the partial-path attribute to include another template or partial file.

<!-- project.html -->
<include partial="header"></include>
<include partial-path="../content.html"></include>

When using the partial-path attribute the file you include does not have to be a partial file which means the file name may not need to start with an underscore.

Partials data and context

Our header partial file example above has hardcoded title and description which does not make it reusable.

We can use template binding to expect a value for the title and description so it can be set to match the pages it is included at.

<!-- _header.html -->
	<p class="description">{description}</p>

By default partial files inherit the context of the template file they are include in.

By declaring the title and description in our project template it will automatically be inherited by the partial included after the declaration.

<!-- project.html -->
<variable name="title">Projects</variable>
<variable name="description">Welcome to the projects page</variable>

<include partial="header"></include>

Creating variable solely to be inherited by the partial may not be a good option because it is not obvious that the declaration is needed by the partial.

To make it more explicit, the include tag takes context data for the partial as data attribute value which the value must be a Javascript object literal.

<!-- project.html -->
<include partial="header" data="{
            title: 'Projects',
            description: 'Welcome to the projects page'