This post is more than 2 years old.
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:
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 do all of that via code... it feels 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:
You then use the Handlerbars API to create a template out of the 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:
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:
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.
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...
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:
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.
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: