Skip to content

Instantly share code, notes, and snippets.

@tomcask
Created January 20, 2017 12:02
Show Gist options
  • Save tomcask/ff98fe878604981d1ff037ad790581aa to your computer and use it in GitHub Desktop.
Save tomcask/ff98fe878604981d1ff037ad790581aa to your computer and use it in GitHub Desktop.
Using partials are templates that can be reused in other templates with hbs.
//http://danburzo.ro/grunt/chapters/handlebars/
//In templating languages, partials are templates that can be reused in other templates. In Handlebars, you use the {{> partial }} helper to include partials. Let's take an example:
//Note: It's important to register the partial before compiling any template that includes it, otherwise it will throw an error.
<script type='text/x-handlebars' id='post-list-template'>
<h2>{{ title }}</h2>
<ul>
{{#each posts}}
<li>{{> post-item}}</li>
{{/each}}
</ul>
</script>
<script type='text/x-handlebars' id='post-item-template'>
<span class='post'>{{ title }} - {{ date }}</span>
</script>
//We have two templates, one for the list of posts, and one for an individual item in the list. The former is a normal template, while the latter is used as a partial. To make everything happen, you'd write in your JavaScript code:
var listString = document.getElementById('post-list-template').innerHTML;
var itemString = document.getElementById('post-item-template').innerHTML;
Handlebars.registerPartial('post-item', itemString);
var template = Handlebars.compile(listString);
template({
title: 'All posts',
posts: [
{ title: 'First post', '10/10/2013'},
{ title: 'Second post', '10/11/2013'}
]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment