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

一曲冷凌霜 提交于 2019-12-03 16:29:00

问题


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>


来源:https://stackoverflow.com/questions/18306382/handlebars-js-use-a-partial-like-it-was-a-normal-full-template

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