Chapter 7. Templating with Handlebars

If you aren’t using templating—or if you don’t know what templating is—it’s the single most important thing you’re going to get out of this book. If you’re coming from a PHP background, you may wonder what the fuss is all about: PHP is one of the first languages that could really be called a templating language. Almost all major languages that have been adapted for the Web have included some kind of templating support. What is different today is that the “templating engine” is being decoupled from the language. Case in point is Mustache: an extremely popular language-agnostic templating engine.

So what is templating? Let’s start with what templating isn’t by considering the most obvious and straightforward way to generate one language from another (specifically, we’ll generate some HTML with JavaScript):

document.write('<h1>Please Don\'t Do This</h1>');
document.write('<p><span class="code">document.write</span> is naughty,\n');
document.write('and should be avoided at all costs.</p>');
document.write('<p>Today\'s date is ' + new Date() + '.</p>');

Perhaps the only reason this seems “obvious” is that it’s the way programming has always been taught:

10 PRINT "Hello world!"

In imperative languages, we’re used to saying, “Do this, then do that, then do something else.” For some things, this approach works fine. If you have 500 lines of JavaScript to perform a complicated calculation that results in a single number, and every step is dependent on the ...

Get Web Development with Node and Express now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.