user1499917
user1499917

Reputation: 101

Reusing templates in handlebars

I am new to JS templating and Handlebars I have a nested JSON structure, often each parent node is a new object / has different structure so recursion is not the solution I think.

My question is Is it possible to call another template from a template in Handlebars?

My background is XSLT

Example:

<script id="entry-template" type="text/x-handlebars-template">
  <div>{{name}}</div>
  .. call template-2
</script>

<script id="template-2" type="text/x-handlebars-template">
  <div>{{name2}}</div>
   .. call template-3
</script>

<script id="template-3" type="text/x-handlebars-template">
  <div>{{name3}}</div>
</script>

.. and so on

Anyone who has some advice?

Best regards, Bob

Upvotes: 9

Views: 4804

Answers (2)

Rich Finelli
Rich Finelli

Reputation: 917

I created a youtube video on partials that explains this: https://www.youtube.com/embed/02J5A3r-Bdk. The video explains creating partials in handlebars in detail and some of the concerns and issues that come a long with and when they are best used and when a server-side include might be better.

Upvotes: 0

Kris Dahl
Kris Dahl

Reputation: 555

That should be pretty easy using partials, and here is a pretty good tutorial.

Essentially though you just need to define the partial

 Handlebars.registerPartial("template-2", $("#template-2").html());

And then utilize it

<script id="entry-template" type="text/x-handlebars-template">
  <div>{{name}}</div>
  {{> template-2}}
</script>

Upvotes: 9

Related Questions