Handlebars Partials | Yext Hitchhikers Platform
What You’ll Learn
In this section, you will learn:
- Why partials are important
- How to construct partials
- Examples of multiple partials in use
Partials
There are times where you have a Handlebars template that you want to be able to use in many other Handlebars templates, but don’t want to have it copied all over the place. In order to have only one copy that gets reused, Handlebars has the concept of ‘partials’. These are indicated using a >
within the Handlebars expression, ex. {{> partial_template}}
Input Data
{
"title": "My Partial Template",
"firstName": "Bryan",
"lastName": "Landen"
}
Templates
main_template.hbs
<h1>{{title}}</h1>
<p>
{{> some_partial_template}}
</p>
some_partial_template.hbs
Hello {{firstName}}! It's great to meet you.
Result
<h1>My Partial Template</h1>
<p>
Hello Bryan! It's great to meet you.
</p>
Partial Block Expressions
In addition to being able to reuse common templates, there’s also the ability to pass data into the partial that can be rendered inside of it.
Input Data
{
"title": "My Super Awesome Search Page",
"firstName": "Bryan",
"lastName": "Landen",
}
Templates
body_of_page.hbs
{{#> layout }}
<h1>Hitchhiker Profile</h1>
<p>Welcome to the profile page for {{firstName}} {{lastName}}!</p>
{{/layout}}
layout.hbs
<html>
<head>
<title>{{title}}</title>
<script src="http://www.yextcdn.com/answers/v1.1.0/answers.min.js" />
</head>
<body>
{{! The page header }}
{{> header}}
{{! The main content of the page }}
{{> @partial-block}}
{{! The page footer }}
{{> footer}}
</body>
</html>
header.hbs
<div id="header">Some header stuff</div>
footer.hbs
<div id="footer">
© Yext, LLC. 2020. All rights reserved. |
<a href="/about.html">About Us</a> |
<a href="/privacy.html">Privacy Policy</a>
</div>
Result
<html>
<head>
<title>{{title}}</title>
<script src="http://www.yextcdn.com/answers/v1.1.0/answers.min.js" />
</head>
<body>
{{! The page header }}
<div id="header">Some header stuff</div>
{{! The main content of the page }}
<h1>Hitchhiker Profile</h1>
<p>Welcome to the profile page for {{firstName}} {{lastName}}!</p>
{{! The page footer }}
<div id="footer">
© Yext, LLC. 2020. All rights reserved. |
<a href="/about.html">About Us</a> |
<a href="/privacy.html">Privacy Policy</a>
</div>
</body>
</html>
Notice how the partial calls two other partials - header and footer - and has an expression {{> @partial-block}}
. That expression is replaced with the content in the partial block expression ({{>layout}}...{{/layout}})
. In this case, it is replaced with:
<h1>Hitchhiker Profile</h1>
<p>Welcome to profile page for {{firstName}} {{lastName}}!</p>