Skip to content

Instantly share code, notes, and snippets.

@dkeeghan
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkeeghan/d9a76c092d8a245f0786 to your computer and use it in GitHub Desktop.
Save dkeeghan/d9a76c092d8a245f0786 to your computer and use it in GitHub Desktop.
Making a Handlebars partial behave a little more like partials in erb.

Props to @keeganstreet for the idea around using JSON passed through as a string. This also allows you to declare the partial name, in a previous partial and load it using a string instead of relying on the name by itself. See the more detailed example (last file) for how this works.

Handlebars.registerHelper('partial', function(name, vars, options) {
var partial = Handlebars.partials[name],
locals = {};
if (!partial) {
console.error('Partial not loaded.');
return 'Partial not loaded.';
}
if (!vars) {
locals = this;
}
if (typeof (vars) === 'object') {
locals.locals = vars;
} else if (typeof (vars) === 'string') {
try {
locals.locals = JSON.parse(vars);
} catch (e) {}
}
return new Handlebars.SafeString(Handlebars.compile(partial)(locals));
});
{{#with locals}}
<ul class="modules">
{{#each modules}}
<li>{{partial partial locals}}</li>
{{/each}}
</ul>
{{/with}}
{{#with locals}}
<div class="module">
<h2>{{title}}</h2>
<p>{{description}}</p>
</div>
{{/with}}
<!-- START simple usage -->
{{partial 'module' '{
"title": "Example title"
"description": "Some description text lorem ipsum
}'}}
<!-- END simple usage -->
<!-- START complex usage -->
{{partial 'load-modules' '{
"modules": [
{
"partial": "module",
"locals": {
"title": "Title 1",
"description": "Description 1"
}
},
{
"partial": "module",
"locals": {
"title": "Title 2",
"description": "Description 2"
}
},
{
"partial": "module",
"locals": {
"title": "Title 3",
"description": "Description 3"
}
}
]
}'}}
<!-- END complex usage -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment