Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Demo of Handlebars, and Why You Should Consider a Templating Engine

DZone's Guide to

Demo of Handlebars, and Why You Should Consider a Templating Engine

· Web Dev Zone
Free Resource

Get deep insight into Node.js applications with real-time metrics, CPU profiling, and heap snapshots with N|Solid from NodeSource. Learn more.

For a while now I've been thinking I need to pick up, and start using, a JavaScript templating engine. I had used a jQuery-based one a few years back, but that project was abandoned and I've yet to really look what - if any - solution would work good for me. Another reason I've not found the time is that a majority of my JavaScript examples are small little demos built for blog posts. When I blog, I try my best to keep my code as simple as possible. I do go all MVC just to demonstrate date formatting. It may not be real world, but it also keeps you focused on the topic I'm trying to discuss.

Today I made the time - and more specifically - made a demo. The demo is stupid. It's not even important. What is important is this:

If you've ever used JavaScript to build strings of HTML, you never realized just how much of a pain that is until you don't have to. You never realized how resistant you are to adding new features - or tweaking the design. You never realized how much you held back - just because of how much of a pain in the rear it was!

I'm probably being overly dramatic, but to me, it feels a lot like ORM. Yeah, it's simple to go into a database client, open a table, and add a new field. But when you can all of that via code... it feel incredibly freeing. You feel yourself trying new and interesting things. In fact, the demo I'm going to show has about twice the features I was planning just because it was so damn easy to add.

That's how I feel today - and any day where my computer makes me smile is a good day. Ok, enough rambling.

I had heard about Handlebars from various people. It's also the templating engine that Ember.js uses. Handlebars works by allowing you to define templates using simple script blocks, so for example, you can write your template in your document like so:

<script id="result-template" type="text/x-handlebars-template">
<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>
</script>

You then use the Handlerbars API to create a template out of block, apply data to it, and then render it to screen. It's all relatively simple, but the docs don't necessarily do a great job I think of demonstrating simple examples in "full" pages so you can see things in context. Here is a trivial example:

 

<!DOCTYPE html>
<html>
<head>
	<title>Test 1</title>
	<script src="js/handlebars-1.0.0.beta.6.js"></script>
	<script id="result-template" type="text/x-handlebars-template">
	<h2>Your Bio</h2>
	<p>
	Your name is {{firstname}} {{lastname}} and you are {{age}} years old.
	</p>
	</script>
    <link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>

	<h2>Render Simple Bio</h2>

	<input type="text" id="firstname" placeholder="First Name"><br/>
	<input type="text" id="lastname" placeholder="Last Name"><br/>
	<input type="number" id="age" placeholder="Age"><br/>
	<button id="demoButton">Demo</button>

	<div id="resultDiv"></div>

	<script>

	document.addEventListener("DOMContentLoaded", function() {

		//Get the contents from the script block 
		var source = document.querySelector("#result-template").innerHTML;
		//Compile that baby into a template
		template = Handlebars.compile(source);

		document.querySelector("#demoButton").addEventListener("click", function() {
			var fname = document.querySelector("#firstname").value;
			var lname = document.querySelector("#lastname").value;
			var age = document.querySelector("#age").value;

			var html = template({firstname:fname, lastname:lname,age:age});
			document.querySelector("#resultDiv").innerHTML = html;

		});
	});


	</script>

</body>
</html>

Notice how I've got a simple template block on top. If you've never seen Handlebars before, or any JavaScript templating engine, you can probably guess which portions of the block represent dynamic portions and which represent static text.

I've got a simple form with a button bound to a simple click listener. Looking at the JavaScript, you can see that first I have to grab the HTML from the template block. I then compile this. This gives me a template that I can reuse to generate output.

My form has a simple click handler. When you hit the button, I pass the values to my template and grab the HTML out of it. You can run this demo here:

http://raymondcamden.com/demos/2012/apr/19/test1.html

Of course, not every template will be a simple set of keys and values. Your template may also need to be dynamic based on the values passed in. Let's look at another example that makes use of both lists and conditionals.

 

<!DOCTYPE html>
<html>
<head>
	<title>Test 2</title>
	<script src="js/handlebars-1.0.0.beta.6.js"></script>
	<script id="result-template" type="text/x-handlebars-template">
	<h2>Your Favorite Things</h2>

	{{#if things}}
		<ul>
		{{#each things}}
			<li>{{this}}</li>
		{{/each}}
		</ul>
	{{else}}

		<p>
		Apparently, you like nothing. Poor you.
		</p>

	{{/if}}
	</script>
    <link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>

	<h2>List of Things</h2>
	<p>
		Enter a comma-separated list of things you like.
	</p>
	<input type="text" id="things" placeholder="Things you like..."><br/>
	<button id="demoButton">Demo</button>

	<div id="resultDiv"></div>

	<script>

	document.addEventListener("DOMContentLoaded", function() {

		//Get the contents from the script block 
		var source = document.querySelector("#result-template").innerHTML;
		//Compile that baby into a template
		template = Handlebars.compile(source);

		document.querySelector("#demoButton").addEventListener("click", function() {
			var things = document.querySelector("#things").value;
			if(things.length) var arrThings = things.split(",");

			var html = template({things:arrThings});
			document.querySelector("#resultDiv").innerHTML = html;

		});
	});


	</script>

</body>
</html>

 

In our template, we've got two things going on here. First is a conditional that checks if "things" is a truthy value (truthy being one of the things that make JavaScript so fun). Within the true part of the conditional we use an each block to enumerate over a set of values.

If you scroll down to the HTML/JavaScript, you can see I'm just asking for you to enter a list of things you like. That value is split into an array and passed (if there were values) to the template. Demo this below..

http://raymondcamden.com/demos/2012/apr/19/test2.html

Let's look at one more example. One of the cooler aspects of Handlebars is that you can add custom functions to the engine. For example, you could write a cowbell function that wraps your results in the beautiful rocking sounds of the cowbell. Ok, maybe not that. But what about something a bit complex - like converting an email address into a MD5 hash that could be used for Gravatar? Yeah - no way that would work...

<!DOCTYPE html>
<html>
<head>
	<title>Test 3</title>
	<script src="js/handlebars-1.0.0.beta.6.js"></script>
	<script src="js/webtoolkit.md5.js"></script>
	<script id="result-template" type="text/x-handlebars-template">
	<h2>You and Your Gravatar</h2>
	<p>
	Your email is {{email}} and your gravatar is:<br/>
	<img src="{{gravatarurl email }}">
	</p>

	</script>
    <link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>

	<h2>Enter Email Address for Awesomeness</h2>
	<input type="email" id="email" placeholder="Email goes here..."> 
	<button id="demoButton">Demo</button>

	<div id="resultDiv"></div>

	<script>

	document.addEventListener("DOMContentLoaded", function() {

		//Tip on using Gravar with JS: http://www.deluxeblogtips.com/2010/04/get-gravatar-using-only-javascript.html
		Handlebars.registerHelper('gravatarurl', function(email) {
		    return 'http://www.gravatar.com/avatar/' + MD5(email) + '.jpg?s=250';
		});

		//Get the contents from the script block 
		var source = document.querySelector("#result-template").innerHTML;
		//Compile that baby into a template
		template = Handlebars.compile(source);

		document.querySelector("#demoButton").addEventListener("click", function() {
			var email = document.querySelector("#email").value;
			if(!email.length) return;

			var html = template({email:email});
			document.querySelector("#resultDiv").innerHTML = html;

		});
	});


	</script>

</body>
</html>

 

Notice in the template we have one simple value, email, and then this: gravatar email. This isn't something built into Handlebars, but rather, injected via the registerHelper function you see in the main script block of the page. You can demo this here:

http://raymondcamden.com/demos/2012/apr/19/test3.html Ok. Time to kick it up a notch. Many moons ago Jason Dean introduced me to the ComicVine API. This is a free API that provides access to their pretty deep database of comic book data. Unfortunately their API isn't very well supported and the documentation is missing a few important details. But I was able to take their service and build the following.

<!DOCTYPE html>
<html>
<head>
	<title>Comic Character Searcher</title>
	<script src="js/handlebars-1.0.0.beta.6.js"></script>
	<script id="result-template" type="text/x-handlebars-template">
	<h2>Results</h2>
	<p>
	Your search returned {{number_of_total_results}} result(s).
	</p>

	{{#each results}}
	<div class="result">
	<h3>{{name}}</h3>
	<p>{{{leftTrim description}}}</p>
	<a href="{{site_detail_url}}">
	{{#if image.super_url}}
	<img src="{{image.super_url}}">
	{{else}}
	<img src="generic.png">
	{{/if}}
	</a>
	</div>
	{{/each}}
	</script>
    <link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>

	Comic Character Search: 
	<input type="text" id="search" autofocus> <i>Results credit ComicVine.com</i>

	<div id="resultDiv"></div>

	<script>
	var baseURL = "http://api.comicvine.com/search/?api_key=4da2671a38f182f28110923ac684980d9658628a&format=jsonp&json_callback=handleResponse&resources=character&field_list=image,site_detail_url,name,description";

	var template;
	var resultDiv = document.querySelector("#resultDiv");

	//Custom helper to trim and remove html as well
	Handlebars.registerHelper('leftTrim', function(text) {
		text = text.replace(/<.*?>/g," ").trim();
		if(text.length > 100) return text.substring(0,100) +"...";
		else return text;
	});

	document.addEventListener("DOMContentLoaded", function() {
		console.log("Business Time");

		var source = document.querySelector("#result-template").innerHTML;
		template = Handlebars.compile(source);

		document.querySelector("#search").addEventListener("keyup", function() {
			var text = this.value.trim();
			if(text.length <= 3) return;

			var reqURL = baseURL + "&query="+escape(text);
			//Credit: http://stackoverflow.com/a/9649610/52160
			var script = document.createElement('script');
			script.src = reqURL;
			document.getElementsByTagName('head')[0].appendChild(script);

		});
	});

	function handleResponse(resp) {
		//console.dir(resp);
		if(resp.error && resp.error == "OK") {
			var html = template(resp);
			resultDiv.innerHTML = html;
		}
	}
	</script>

</body>
</html>

 

This application uses JSON/P and the ComicVine API to let you search against their character database. A good search string is "spider". Obviously it doesn't have everything in there, but it's fun to see what's there. Oh yeah - be sure to search for "Beyonder" - the best thing to come out of Marvel in the 80s. You can demo this here:

 

Node.js application metrics sent directly to any statsd-compliant system. Get N|Solid

Topics:

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}