Using Handlebars with Backbone and RequireJS and Precompiling templates

PRE-COMPILING HANDLEBARS TEMPLATES WITH NODE

Note: I did discover something a little strange...that this process doesn't work if there is only one template file that you are compiling. When my 'templates' dir had more than one .hbs file in it, then everything worked just fine. Not sure why that is.

Even more strange: I later found that even if you only have one template to compile, you can still get things to work by changing your syntax in your view. In my example below (the backbone view), I set the 'template' property to Templates['my-view.hbs']. I found that you can also set the value to Handlebars.templates['my-view.hbs']. In this case, it will work even if you have only one template file that gets compiled.

 

1. Create your template files and put them all in one folder (I put mine in a 'templates' folder that sits next to the 'js' folder of my project. I used the .hbs extension. Note that you should NOT have <script> tags enclosing your templates.

 

2. Install node handlebars (globaly)

npm install -g handlebars

 

 

3. Cd into the directory where your templates are and compile them all into one .js file (called compiled-templates.js) like this:

handlebars --amd *.hbs -f compiled-templates.js

 

 

4. Here's a sample of how to use the compiled-templates in your view. Just include compiled-templates.js in your define (aliased as Templates) and then set this.template to Templates['template name']. This example assumes that one of your uncompiled template files was named my-view.hbs:

define(['backbone','underscore','jquery', 

"../../templates/compiled-templates"

],

function ( Backbone, _, $, Templates) {

var MyView = Backbone.View.extend({

template: Templates['my-view.hbs'],

render: function(){

this.$el.html(this.template({somevar: "HIIIIIIII"}));

return this;

}

});

return MyView;

});

 

PRECOMPILING HELPERS

Create a requirejs module and put all your helpers in it:

 

define(['handlebars'], function (Handlebars) {
Handlebars.registerHelpers('myHelper', function(){...});
Handlebars.registerHelpers('anotherHelper', function(){...});
});

 

 

 

BEFORE I FIGURED OUT HOW TO PRECOMPILE, I WOULD COMPILE TEMPLATES AT RUN TIME USING THESE STEPS

1. Make sure handlebars is specified in the bower install script (in component.json)

2. Make sure the requirejs text plugin is also installed in the bower script.

3. Make sure that a 'path' is specified to the handlebars library in main.js (it also needs to be shimmed and exported to make it amd compliant)

4. Create a templates directory in the 'app' folder

5. Inside that 'templates' dir create a sample template file (it's called sample-template.hbs):

 

<h3>{{someVar}}</h3>

<select>{{#each selectOptions}}

<option value="{{id}}" {{#if selected}}selected="true"{{/if}}>{{label}}</option>

{{/each}}

</select>

 

 

6. Create a module that compiles all templates (the file is called compiled-templates.js and it's located in the 'app' dir)

 

define([

'handlebars',

'text!../templates/sample-template.hbs',

'text!../templates/main-menu.hbs'

], function(Handlebars, SampleTemplateFile, MainMenuFile){



return {

SampleTemplate: Handlebars.compile(SampleTemplateFile),

MainMenuTemplate: Handlebars.compile(MainMenuFile)

}



});

 

 

7. Create a view that depends on the 'compiled-templates' module

 

define([

"jquery",

"underscore",

"backbone",

"handlebars",

"compiled-templates"

], function($, _, Backbone, Handlebars, JST){



var SampleView = Backbone.View.extend({



template: JST.SampleTemplate,



render: function(){



var selectOptions = [

{id:1, label:"coach"},

{id:2, label:"quarterback", selected: true},

{id:3, label:"kicker"}

];



this.$el.html(this.template({someVar:"HIIIIIII", selectOptions: selectOptions}));

return this;

}



});



return SampleView;

 

 

NOTE: If you didn't want to use the precompiled template (for some reason), you could compile it directly in the view like this (note that instead of depending on the 'precompiled-templates' module, you would have to depend on the template file directly, using the text plugin):

 

define([
"jquery",
"underscore",
"backbone",
"handlebars",
"text!../../templates/sample-template.hbs"
], function($, _, Backbone, Handlebars, PlainTextTemplate){

var SampleView = Backbone.View.extend({

template: Handlebars.compile(PlainTextTemplate),

render: function(){

var selectOptions = [
{id:1, label:"coach"},
{id:2, label:"quarterback", selected: true},
{id:3, label:"kicker"}
];

this.$el.html(this.template({someVar:"HIIIIIII", selectOptions: selectOptions}));
return this;
}

});

return SampleView;

});

 

 

Add a Comment...

 

Comments

When some one searches for his essential thing, so he/she wants being available that at length, thus that thing is maintained over here. - 9/28/2016

A person essentially assist to produce seriously posts I'd state. That may be the first time I frequented your website page and so far? I amazed with the research you intended to make this actual publish incredible. Great job! - 9/19/2016

Repaoring automobiles can be vеry confusing and finding somᥱone qualified to mɑke thᥱ correct repairs iss bescoming ᥱven moгe difficult. Do yoᥙ pay it each timе or for just cеrtain types of repairs. Нowever, moѕt doorbells connect ѡith јust ttwo low-voltage wires. - 9/16/2016

Hey! Someone during my Facebook group shared this website along with us so I arrived at give it a look. I'm definitely loving the info. I'm bookmarking and will also be tweeting this to my followers! Wonderful blog and fantastic design. - 9/15/2016

May I just say what a comfort to discover someone who genuinely knows what they're discussing over the internet. You actually understand how to bring a problem to light and make it important. More people must check this out and understand this side of the story. I can't believe you aren't more popular since you certainly have the gift. - 9/12/2016

Hey there just wanted to give you a quick herads up and let you know a few of the pictures aren't loading properly. I'm not sure why but I think its a linking issue. I've tried it in two different browsers and both show the same results. - 9/11/2016

Greg Sancs dpes not worry аbout ᴡɦere his next customer іѕ сoming from in any ߋf һis 20 repair shops ɑcross the country. Ϻake sսгe to equip ʏоur auto body shop with mⲟst recent machines and new technologies. Іt iѕ аlways ǥood tⲟ check yor ϲaг for repars tҺat need too bbe madе. - 9/07/2016

Terrific article! This is certainly the type of info that are meant to be shared across the internet. Shame on Google for no longer positioning this publish higher! Come on over and seek advice from my website . Thanks =) - 8/30/2016

http://undeclaiming.xyz norsk kasino http://undeclaiming.xyz - norsk kasino - 5/21/2017

com) website is worth that long shot at winning a prize of $2 million upfront, $10,000 a month for life, and a Lincoln MKZ vehicle (even though no one has won other big super prizes for the past six months when advertised), then play on, especially if you see this as a fun diversion. FREE Lottery Winning Tips and Secrets e - Course packed with secrets and tips on how to win the lottery with free lottery software at. Applicants need just three pieces of information from their green card l - 5/19/2017

I thiunk this iss among the moat significant information foor me. And i'm glad reading your article. But want to remark on few general things, The web site stye is ideal, the articles is really excellent : D. Good job, cheers - 5/14/2017

Good information. Lucky me I ran across your site by accident (stumbleupon). I've book-marked it for later! - 5/13/2017

The quite a few numbers of porn stars who apply to hitch our company go through a rigorous selection process to establish that only the most certified get by. - 5/05/2017

I must thank you fоr the efforts you've put in penning this site. I am hoping to checқ out the same high-grade content by you in the futuгe as well. In fact, your creative writing abilities has inspiгeԁ me to get my very own weЬsite now ;) - 5/04/2017

viagrasansordonnancefr.com viagrasansordonnancefr - 5/03/2017

agree to this casino online where you can collect legal money with the serve of this lightPlaying online casino games , check this casino - 4/23/2017

Sleep apnea is a very difficult thing to live with, both for the sufferer and for people living and sleep with him or her. If you fit into either of these categories, then you know just how frustrating it can be. Read through the tips found in this article to learn the best way to survive this problem! Try using a mouth guard that's custom-fitted for you. These are made especially for those suffering from sleep apnea. If you don't have CPAP, then this guard is an excellent alternative. Also - 4/20/2017

large website! inexact tag in up the humongous work. visit my website only if you are overwhelming 21 check this online sextoys portal, email server , buy Buy Dildo - 4/18/2017

thanks for this countless edifying website, keep up the momentous undertaking check out this casino online offers , buy sex toys - 4/04/2017

Good article! We will be linking to this great post on our website. Keep up the good writing. - 3/29/2017

It's an amazing piece of writing in favor of all the online users; they will get advantage from it I am sure. - 3/20/2017

Hello there! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I'm using the same blog platform as yours and I'm having trouble finding one? Thanks a lot! - 3/13/2017

agree out this online casino where you can prevail in genuine money with the avoid of this enchiridionPlaying roulette online , buy sex toys - 3/11/2017

美容に良い青汁なら「ふるさと青汁」がおすすめです。 ネットの評判も高評価で、ふるさと青汁は青汁の中でも最も注目されている青汁といえます。 でも気になるのは味ですよね? ご安心ください。ふるさと青汁は抹茶みたいな感じで飲みやすくて大人気なんです! そのままでも美味なのですが、豆乳に混ぜたりヨーグルトに混ぜて飲んでもおいしくて飲みやã - 3/07/2017

Today, almost each one of people is registered on social network bandwagon.Understand that - don't ask him if however like a cigarette.People can look at your business the same way as your items.Them? s important to find a very good senior care to ensure that your elder? s needs are actually met.Even so, because of the lethal nature of your disease doctors generally agree the fact that presence of rectal hemorrhaging, even in. Countless other ideas exist as to how kids makes money.Brand-new are - 3/07/2017

study ended this online casinos where you can prevail in legitimate money with the usurp of this enchiridionPlaying bitcoin casino bonus , buy sex toys - 3/05/2017

check doused this online casino where you can prevail in genuine notes with the avoid of this guidebookPlaying online casino bonus , buy sex toys - 3/01/2017

Instead of the advertisers sending a message with a targeted audience that behaves or dismisses the proactive approach, online consumers seek outside information and advertising.Hallucinogens are often bought by teens at raves or dance dance clubs.ANY card can be pulled every day to set an intention for the day and also facilitate argument at dinner or well before bed.And I'll see why I? m having countless problems with my elderly son and why he is on drugs.In comparison with the ratio of cost w - 2/25/2017

thanks for this colossal revealing website, obstruct up the massive jobless check out this online casinos offers , buy sex toys - 2/24/2017

Okay wrap this section up by fore warning you that in 2007 Managed to get an email from Freedy, after not hearing from him for years.Subsequently, instead of creating engineered so is meant for a audience, you can rotation several bent on tempting certain market demographics merely.All these traits of dynamic command, tenacity, and drive will be admirable, even desirable; badly channeled and controlled, yet, these very traits that maketh an Alpha man is usually his own undoing.The moral belongin - 2/23/2017

thanks due to the fact that this great illuminating website, living up the skilled jobless check out this online casino offers - 2/20/2017

Yow will discover out several well known and reliable driving drunk defense attorneys online.Bunny Temperament - An Interview While using the Experts - free article for ArticleCity.These are not interactive with men and women only with other finches knowning that makes them happy.But if your teen has an interest in a particular career i.It is possible to join an affiliate program and become promoting your product online literally in a few moments. ? Accessorise? scarves, hats and gloves are com - 2/18/2017

Actually his &quot;Seven Heavens&quot; are borrowed with a very old Jewish mobile.You can discover many cliparts with merest modifications yet with completely different subject matters either, thus you will find there's continuing process of making, producing and using the hands down school cliparts by many individuals.Know the current events of today when this will show that you will be in tune with this? s going on the across the world.Here are a couple tips and tricks to build that banner rea - 2/17/2017

thanks towards this countless revealing website, keep up the momentous work check out this online casinos offers - 2/14/2017

study ended this online casinos where you can collect genuine kale with the avoid of this enchiridionPlaying online baccarat - 2/08/2017

thanks towards this colossal edifying website, keep up the momentous jobless check out this casino online offers - 2/07/2017

thanks due to the fact that this countless illuminating website, living up the skilled jobless check out this online casino offers - 2/05/2017

Wow, amazing blog layout! How long have you ever been running a blog for? you make blogging glance easy. The entire glance of your web site is excellent, let alone the content! - 12/31/2016

What's Heading down i'm new to this, I stumbled upon this I have discovered It positively useful and features aided me out loads. I am hoping to contribute & help different customers like its aided me. Great job. - 11/18/2016

I would like to thank you for tthe efforts you've put in writing thnis web site. I'm hoping the same high-grade web site post from you in the upcoming as well. Actually yur creative writin abilities has inspired me to get mmy own web site now. Actyally the blogging is spreading its wikngs fast. Your write up iss a great example of it. - 11/16/2016

Fastidious answers in turn on this matter with solid arguments and describing everything concerning that. - 11/15/2016

Very soon this website will be famous amid all bloggijg and site-building users, due to it's fastidious articles - 11/12/2016

Youu sҺould ɑlso determine what level of sales mɑy justify extending үoᥙr hours ɑnd ᴡhether yyou աant to ߋwn morе than one shop. The time you save by not hаving to track someߋne dօwn is time faг ƅetter spent elsewheгe. Here are a few ways you can find the Ƅest company for ʏоur neeԁs. - 11/01/2016

I each and every time emailed this blog post page for all my associates, for the reason that if love to read it then my links will too. - 10/08/2016

hello there and be grateful for your information - I have got certainly picked up anything new from below. I did so however expertise several technical issues using this website, as I experienced to reload the site a great deal of times previous to I was able to buy it to load correctly. I was wondering should your hosting is OK? Not that I'm complaining, but slow loading instances times will sometimes affect your placement in the search engines and could damage your quality score if a - 10/02/2016

It's amazing to pay a visit this web page and reading the views of all mates regarding this post, while I am also keen of getting knowledge. - 1/20/2017

Onnce yоu miɡht have fߋund something tһat yοu ᴡould like tο make usᥱ օf, maintain ʏoᥙr number availaƅlᥱ ԝith you whatsoever tіmеs. Ƭhᥱ vehicle owner ѡith roadside assistance ᴡho finds her carr inoperable neeԁ only call а toll free numbеr for immedіate assistance. Annd with ⅼong-lasting LED lights, уouг strobes ᴡill kеep yoᥙ sade ᴡithout yyou neеding tо concern yⲟurself wіth changing bulbs all of thhe time. - 1/10/2017