O'Reilly logo

Web Development with Node and Express by Ethan Brown

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required