Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError applying precompiled Handlebars templates with a context

Tags:

Pardon the noob question but I simply can't get precompiled Handlebars templates to do anything but barf out

TypeError: 'undefined' is not a function (evaluating 'templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data)')

each time I apply a context to a (precompiled) template.

Given the following files and contents:

  • hello.handlebars: <p>Hello, {{name}}</p>
  • templates.js: the result of compiling hello.handlebars via handlebars hello.handlebars -f templates.js
  • index.html: includes Handlebars RC1 runtime in the head and this for the body:

    <body id="body">   <script src="templates.js" type="text/javascript" charset="utf-8"></script>   <script type="text/javascript" charset="utf-8">     var compiledTemplate = Handlebars.templates['hello'];     var html = compiledTemplate({ name: 'World' });     document.getElementById('body').innerHTML = html;   </script> </body> 

Calling compiledTemplate() throws that error above no matter what I do--yet I'm able to get client-side templates to compile and display just fine. All the walkthroughs and tutorials I've seen skip through this like its obvious so I must be missing something silly. Any ideas?

like image 795
ele Avatar asked Feb 23 '14 03:02

ele


2 Answers

Be sure to match the versions of the Handlebars server and client packages. A way to check the version of the compiled template is the following:

handlebars a_template_of_yours.handlebars | grep "compilerInfo"

It should output something like this:

this.compilerInfo = [4,'>= 1.0.0'];

The first value is the Compiler Revision, which should match the output of the following code on your browser:

Handlebars.COMPILER_REVISION

If you used npm to download your Handlebars compiler, specify the version which you need. Here is an example for handlebars.runtime-v1.3.0.js:

npm install [email protected] -g

like image 102
biomorgoth Avatar answered Oct 16 '22 05:10

biomorgoth


The problem for me is that currently (June 2014), the 2.0 release on GitHub is marked alpha https://github.com/wycats/handlebars.js/releases.

If I install handlebars via bower, it selects the latest stable release. v1.3.0.

npm install handlebars, however, installs the ~2.0.0-alpha.4 version.

Solution: update the version in bower.json to ~2.0.*, and run bower update.

like image 25
Tim Avatar answered Oct 16 '22 06:10

Tim