Joe Karlsson
progress. tech. cats. coffee. art. food. photog. mpls.
Intro to Jade - A high performance template engine for JavaScript
When you build a JavaScript application, you'll almost certainly use some JavaScript templates. Rather than use a library like jQuery (or vanilla JavaScript) to update your HTML when values update, you can use templates, which cleans up your code hugely.
Obviously we don't just send text to the client, we usually send back HTML in standard web applications and deal with dynamic data in our applications as well.
Template engines offer us the ability to bind static HTML to dynamic data and output the result of the two as our HTML responses to serve our HTTP requests.
There are many template engines available:
"Template engines offer us the ability to bind static HTML to dynamic data and output the result of the two as our HTML responses to serve our HTTP requests."
All template engines have the same purpose of allowing us to pass data to our template engine to dynamically render static output
The main difference between them is more or less syntax of how we write our templates.
In Express, regardless of the template engine used the syntax to call them is the same using the res.render() function.
As noted before, the res object is the object we use to send an HTTP response back to the client based on the HTTP request our application received.
//When we call the render() function we pass it an object of data values to bind to output
app.get('/', function (req, res) {
res.render('index', { userName: 'Jason', email: 'jaywon@dark.net'});
});
Which would be passed to a template like:
//index.jade
h1
Hello #{username}
div
Your email is: #{email}
//index.hbs
<h1>
Hello {{username}}
</h1>
<div>
Your email is: {{email}}
</div>
Jade (.jade)
Handlebars (.hbs)
Both templates would render the exact same HTML output
To tell Express which template engine we will be using we need to:
$ npm install --save pug
//Tell Express which Template engine we are using by NPM module name
app.set('view engine', 'pug');
//Tell Express where our template files live
app.set('views', './views');
NOTE: Express will automatically append the file extension when using res.render() but needs to know where to look.
app.locals - Used for defining application level variables that are accessible anywhere in your application
Express has gone through major revisions between version 3.x and 4.x. When looking at documentation make sure it is referencing the proper version you are using.
Even though we don't handle HTTP headers manually as we did previously, they are still accessible on the req object. Take a look at the docs for the Request/Response objects to see what properties are available.
By Joe Karlsson
Intro to Jade - A high performance template engine for JavaScript