Templates - abbernie/web-dev-sp17 GitHub Wiki
Often a site will have many different pages that all share the same basic layout but have different content. For example, all the pages in your site might have the same header at the top and footer at the bottom. If you did everything by hand, you'd have to update all of the pages if you ever made a change to the header or the footer, and once you have more than just a few pages, that can make your site hard to manage. That's where templates come in. A template serves as the frame of a page, and leaves areas for the content, which will be different on different pages.
When you want to create an HTML page once and use it as template for different pieces of data, Express provides the render()
function. We'll be using a templating language called Handlebars.
The render()
function takes two parameters: the name of the template, and an object containing the data that will go into the template.
app.get("/",function(req,res){
var mydata = {
title: "Things You Never Knew",
date: "November 24, 2014",
articleText: "Donec diam nibh, imperdiet ac lacus sit amet, accumsan tincidunt urna."
}
res.render("page",mydata);
});
The string "page" in the render function refers to the name of the template file. In this case, the file would be called page.handlebars
. It will contain HTML and Handlebars' specially formatted template tags.
In the Handlebars template, create placeholders for the data (also known as template tags), using the same names as the property names of the data object -- in the example above, we have title
, date
, and articleText
. So the Handlebars template might look like:
<h1>New York Daily News</h1>
<h2>{{title}}</h2>
<h3>{{date}}</h3>
<p>{{articleText}}</p>
To install Handlebars for use in your Express project, go to your project folder in Terminal and install with npm:
npm install --save express-handlebars