Handlebars templates are pretty awesome to work with. The quickest way to get started is to put a template in a script block and use the "text/x-handlebars-template" content-type.

<script id="badtemplate" type="text/x-handlebars-template">
  <p>Hi, I'm a bad way to put a template on a page.</p>
</script>

This presents a few problems:

  • Editing templates is less than fun. You get huge sections of template code that you must navigate through. My IDE (VS2010 and VS2012) do not know what is going on.
  • Template reuse is impossible since they're just built on a single page. This may be acceptable for small SPAs but I doubt it.

I'm sure there are a bunch of tools out there for template loading. Not feeling like learning another framework, tool, or package today, I decided to write my own in about an hour.

What I wanted was a way to load templates on page load or on demand.

<script type="text/javascript">
  // Registration with the page
  templateLoader.register({ key: "ipcheck", path: "/content/templates/ipcheck.html" });
</script>

Then a way to access those templates when I needed them.

<script type="text/javascript">
  // Use the templates
  function doSomething(obj)
    // compile the template
    var ipcheckTemplateCompiled = Handlebars.compile(templateLoader.html("ipcheck"));

    // run the temlate
    var html = ipcheckTemplateCompiled(myobj);

    // do stuff
  })
</script>

The code manages this whole process for me:

https://github.com/bmancini55/template-loader

This was more an exercise in showing how simple it can be to load templates. I could make this code a lot better, but frankly, it works.