I have a template that I want to use both as a partial, and by itself from javascript.
In order to use a partial, it must be registered via Handlebars. registerPartial . Handlebars. registerPartial('myPartial', '{{prefix}}');
Handlebars is a simple templating language. It uses a template and an input object to generate HTML or other text formats.
Partials are basically functions that return functions with some already predefined arguments and need some arguments to be completed. Let's say you have a function with several arguments to be set, but you don't want to set the majority of arguments over and over again because you need it more than once.
If your templates are precompiled, you can access your partials via Handlebars.partials['partial-name']()
as well as call them from a template via the {{> partial}}
helper.
This is nice because you can then write a utility function for rendering a template whether it be a full blown template or partial.
ex:
function elementFromTemplate(template, context) { context = context || {}; var temp = document.createElement('div'); temp.innerHTML = templates[template] ? templates[template](context) : Handlebars.partials[template](context); return temp.firstChild; }
myDiv.appendChild(elementFromTemplate('myPartial', context));
myDiv.appendChild(elementFromTemplate('a-whole-template'));
Hope this helps anyone else who wants to use Handlebars like I do.
It's easier to do it the other way around - to compile all your templates as normal templates, then make them available as partials:
Handlebars.partials = Handlebars.templates
This makes it possible to use your templates as usual, and as partials as well:
{{> normalTemplate}}
To render a partial from javascript you can use
Handlebars.partials["myPartial"]()
To use a partial from a template, simply include {{> partialName}}
.
<script id="base-template" type="text/x-handlebars-template">
<div>
{{> person}} <!-- This is the partial template name -->
</div>
</script>
<script id="partial-template" type="text/x-handlebars-template">
<div class="person">
<h2>{{first_name}} {{last_name}}</h2>
<div class="phone">{{phone}}</div>
</div>
</script>
<script type="text/javascript">
$(document).ready(function() {
var template = Handlebars.compile($("#base-template").html());
//Aliasing the template to "person"
Handlebars.registerPartial("person", $("#partial-template").html());
template(yourData);
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With