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:
For example we have 2 partials that are implemented as below:
- Partial 1:
userInfo.hbs
- Partial 2:
userProjects.hbs
Then in template.hbs, we can call those 2 partials
template.hbs
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:
Inside userAccount.hbs
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:
Implementation of the userAccount.hbs need to update:
The output will be the same for both cases:
<div>
<p>yehuda_katz</p>
<p>katz_yehu@example.com</p>
</div>