BETAThis is a new service – your feedback will help us to improve it.

Views and templates

Our web app will eventually send HTML pages to users in response to their requests. These pages won't be static—they'll change based on data stored in the app.

For example, a blogging app may store each blog post as an entry in a database.

When the user visits the front page of the blog, they will see a web page with a list of the most recent blog posts.

It wouldn't be practical to store this list as a HTML file—we'd need to change it every time we published a new blog post. Ideally, we want the list to update automatically.

Instead, we need to use a template that the app will use as a starting point. The app will combine the template with real data, building a list that is always up to date.

Configure views

Every screen your app shows a user is a view.

Our blogging app might have at least two views:

  • A list of recent posts
  • A detailed view of a single post

Each view is saved as a template file, and we can write code telling the app what circumstances to show that view under.

Let's configure our app to use views and templates.

Go to your server.js file and change it to include two extra lines:

const express = require('express')

// Include Nunjucks code
const nunjucks = require('nunjucks')

let server = express()

// Set up Nunjucks
nunjucks.configure(__dirname + '/views', {
  autoescape: true,
  express: server
});

server.use(express.static(__dirname + '/static'))

server.listen(3000, function(){
    console.log("Server is running")
})

The two extra blocks of code set up a templating language called nunjucks, and tell Express that our views are located in the /views folder.

Nunjucks isn't part of Express, so we need to install it. Make sure the terminal is in your /my-app folder, then run:

npm install --save nunjucks

We'll discuss nunjucks later in the module.

Create a view

Let's create the /views folder now. Create a blank file called index.njk inside that folder. Write any message inside that file.

Restart your app.

If your app is already running, you need to stop it by closing the current terminal tab, and restart it by clicking the blue play button. Otherwise we won't see the changes we made.

Even if we did everything right, we still won't see the view we've just created in the browser. We'll just see the familiar Cannot GET / error.

In the next lesson we'll discuss why.

Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Web servers
  1. Create your serverP
  2. Create your appP
  3. Node and the terminalP
  4. More about the terminalP
  5. Web frameworksP
  6. Using ExpressP
  7. Serving static files
  8. Views and templates
  9. Routing
  10. Real data
  11. Includes
  12. Get confident with Express
  13. Build your app in ExpressP