#104 Handlebars Template To String

You can compile a handlebars string using the code below.

But what if you wanted to load the string from an existing .hbs template?  You can create a utility function like this:

Then use it in your code like this:

This will load and compile the template demo.hbs and also pass it a context, here is an example demo.hbs.

This will generate the string:


The helper function does the following:

  • Load the template using the lookup method
  • Define a component and merges the context object with it
  • Instantiate the component
  • Append it to DOM (to force a render) – nothing gets displayed because of the display:none


Thanks to Matt Roberts for suggesting this tip and pointing me to http://stackoverflow.com/questions/27950413/render-ember-js-hbs-template-to-a-string/35625858