Search code examples
templatinghandlebars.jsclient-side-templating

Way to organize client-side templates into individual files?


I'm using Handlebars.js, and currently all my templates live inside script tags which live inside .html files housing dozens of other templates, also inside script tags.

<script type="text/template" id="template-1">
  <div>{{variable}}</div>
</script>

<script type="text/template" id="template-2">
  <div>{{variable}}</div>
</script>

<script type="text/template" id="template-3">
  <div>{{variable}}</div>
</script>

...

Then I include this file on the server-side as a partial.

This has the following disadvantages:

  1. A bunch of templates are crammed into HTML files.
  2. Finding a given template is tedious.

I'm looking for a better way to organize my templates. I'd like each each template to live in its own file. For example:

/public/views/my_controller/my_action/some_template.html
/public/views/my_controller/my_action/some_other_template.html
/public/views/my_controller/my_other_action/another_template.html
/public/views/my_controller/my_other_action/yet_another_template.html
/public/views/shared/my_shared_template.html

Then at the top of my view, in the backend code, I can include these templates when the page loads, like this:

SomeTemplateLibrary.require(
    "/public/views/my_controller/my_action/*",
    "/public/views/shared/my_shared_template.html"
)

This would include all templates in /public/views/my_controller/my_action/ and also include /public/views/shared/my_shared_template.html.

My question: Are there any libraries out there that provide this or similar functionality? Or, does anyone have any alternative organizational suggestions?


Solution

  • I ended up using RequireJS, which pretty much let me do this. See http://aaronhardy.com/javascript/javascript-architecture-requirejs-dependency-management/.