Remote handlebars templates with jQuery
I recently discovered handlebars, a javascript template framework. If you take a look at the tutorials on the website itself you will notice that all of the tutorials focus on declaring your templates in <script> tags.
The project itself does not support remote templates, unless you have them precompiled...
This very brief guide is to illustrate to you how you would automatically load and compile remote templates using jQuery.
First create a template called post.handlebars (or whatever else you decide) and insert the following code:
<div class="entry"> <h1>{{title}}</h1> <div class="body"> {{body}} </div> </div>
Next add the following line into your main html file (e.g. index.html):
<link rel="prefetch" type="application/x-handlebars-template" src="handlebars/post.handlebars" data-template="post" />
Next add the following javascript to your markup (or separate javascript file). Remember it's usually better to add the markup at the bottom of your body.
var handleBarsTemplates = {};
$("link[type='application/x-handlebars-template']").each(function() {
var url = $(this).attr("href");
var templateName = $(this).data('template');
$.get(url, function(data) {
var template = Handlebars.compile(data);
handleBarsTemplates[templateName] = template;
You can access the templates by using the following javascript:
handleBarsTemplates.post({title: "Easy Handlebars", body: "This was really simple wans't it"});
See! Very easy, any questions? I will do my best to help.