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

扶醉桌前 提交于 2019-12-03 04:55:16

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!