Skip to main content

Partials

One of the most used features of Handlebars is partials. Partials are reusable template fragments, basically “components” you can include inside other templates.

Calling the partial is done through the partial call syntax:

{{> myPartial }}

For example we have 2 partials that are implemented as below:

  • Partial 1:

userInfo.hbs

<p>{{firstName}} {{lastName}}</p>
  • Partial 2:

userProjects.hbs

<ul>
{{#each projects}}
<li>{{this.projectName}} - {{this.company}}</li>
{{/each}}
</ul>

Then in template.hbs, we can call those 2 partials

template.hbs

{{> userInfo}}
{{> userProjects}}

If we apply below input to the template.hbs

{
"firstname": "Yehuda",
"lastname": "Katz",
"projects": [
{ "projectName": "Project A", "company": "Company X" },
{ "projectName": "Project B", "company": "Company Y" },
{ "projectName": "Project C", "company": "Company Z" }
]
}

The HTML output would be:

<p>Yehuda Katz</p>
<ul>
<li>Project A - Company X</li>
<li>Project B - Company Y</li>
<li>Project C - Company Z</li>
</ul>

Passing data to partials​

You can pass context explicitly:

{{> userAccount account}}

Inside userAccount.hbs

<div>
<p>{{username}}</p>
<p>{{email}}</p>
</div>

The input data would look like this:

{
"account": {
"username": "yehuda_katz",
"email": "katz_yehu@example.com"
}
}

If you want to use a differnt name for the partial argument, like I want to change the argument name from account to data, you can pass context like this:

{{> userAccount data=account}}

Implementation of the userAccount.hbs need to update:

<div>
<p>{{data.username}}</p>
<p>{{data.email}}</p>
</div>

The output will be the same for both cases:

<div>
<p>yehuda_katz</p>
<p>katz_yehu@example.com</p>
</div>