Handlebars.js: Use a partial like it was a normal,

2019-03-17 19:40发布

问题:

I have a template that I want to use both as a partial, and by itself from javascript.

回答1:

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.



回答2:

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}}


回答3:

To render a partial from javascript you can use

Handlebars.partials["myPartial"]()


回答4:

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>