Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I precompile partials for handlebars.js?

I'm using handlebars.js and I want to start precompiling everything, but I can't seem to find a way to precompile the partials. The majority of my templates are actually partials. I tried just treating my them like regular templates, but then calling them as a partial doesn't work.

Is there any way to precompile partials, or, alternatively, call one template from within another template?

like image 351
Nathan Friedly Avatar asked Aug 17 '12 23:08

Nathan Friedly


People also ask

How do I use precompiled handlebars templates?

First you need to install handlebars with node by running this command. If you don't have node, go ahead and install it first. It's really quick and painless. Then with all of your templates in that folder, open up the command prompt, navigate to the folder right above the js folder.

How do you include partials in HBS?

hbs' files: To get the reference to these files to work we need to registers these files, which are partials using: '__dirname' is the root folder of our project and link to the subfolder '/views/partials' as seen here: Our code in our 'home.

How do I compile handlebars templates?

Precompiling Templates Inside NodeJS If you wish to precompile templates from inside NodeJS--without invoking "handlebars" from the command line--that can be done with Handlebars. precompile. Transmit the string result of this function to your clients, and they can in turn parse that with Handlebars. template.


2 Answers

I found an even better method: precompile all your partials as templates, then right before you use them in your code, add this line:

Handlebars.partials = Handlebars.templates; 

The improvements are 1) it's shorter and 2) it doesn't loose any custom helpers you might pass in when calling the parent template.

like image 196
Nathan Friedly Avatar answered Sep 22 '22 13:09

Nathan Friedly


As mentioned here on GitHub, there has been a -p flag added to the Handlebars CLI.

So you can use handlebars my_partial.handlebars -p -f output.js

like image 43
moollaza Avatar answered Sep 19 '22 13:09

moollaza