I am struggling somewhat with pre-compilation of templates in Handlebars. My jQuery Mobile project is getting pretty big template-wise and I wish to pre-compile the template
Here is the way I do it:
We will just assume all your template variables are in a variable called context
:
var context = {
name: "Test Person",
...
};
Create a directory containing all your templates (we'll call it templates/
)
Add your templates here, called filename.handlebars
.
Your directory structure:
.
└── templates
├── another_template.handlebars
└── my_template.handelbars
First go to your root directory, then compile your templates with the npm CLI program:
handlebars templates/*.handlebars -f compiled.js
New directory structure:
.
├── compiled.js
└── templates
├── another_template.handlebars
└── my_template.handlebars
Include the compiled.js
in your HTML page after you include the runtime:
Render your templates using the global Handlebars
object:
// If you used JavaScript object property conform file names
// Original filename: "my_template.handlebars"
Handlebars.templates.my_template(context)
// if you used special characters which are not allowed in JavaScript properties
// Original filename: "my-template.handlebars"
Handlebars.templates["my-template"](context)
Note the file extension .handlebars
. It is automatically stripped when compiling the templates.
Extra: if you use one of the Jetbrains IDEs together with the Handlebars/Mustache plugin you even get quite a good editor support.