Express.js supports a variety of template engines. Get an introduction in this video.
- [Lecturer] Year back when the first dynamic websites appeared it was usual to make html code and program logic very often in one huge file. So a web application basically consisted of functions that concatenated bits and pieces of html code until it was ready to be dumped to the browser. This was of course extremely hard to maintain. The change the design of a website one would basically need to rewrite all of it and it was impossible for a non-programmer like PRO Designer to change the user interface in any way.
So it comes that today templates are used to separate presentation from logic. This means a template is the container for the contents filled by the application. Everything concerning the way a page looks, lives in the template, everything concerning the program logic lives in the application. This principal is also referred to as separation of concerns. A template engine provides an interface to fill templates with data and render them, and very often comes with its own syntax for creating templates.
Express is very agnostic when it comes to template engines. Any engine that provides a specific interface can be plugged into the framework. Looking at a screen shots from Express wiki, we see that around 20 engines are known to work with Express. Choosing the right one is mostly a matter of preference. Most importantly you should feel comfortable with the syntax. Today the most popular template engines are, Pug, EJS and Handlebars.
To understand the difference between them let's compare the syntax of Handlebars and Pug. With Handlebars you see that the syntax is very similar to regular html, it just uses double curly brackets to create placeholders for dynamic data. Using it is easy because there is no new markups syntax to learn. Pug on the other hand has a completely different syntax. It uses white spaces in the form of indentation to describe the structure of the document.
This is shorter but we have to learn a new syntax. Of course the end result rendered to the browser would be the same for each template engine. For this course we will use Pug as it's very commonly used and also the default in Express.
- Creating a server with Express and pure Node.js
- Handling errors in Express
- Creating routes
- Using templates
- Working with the Pug template engine
- Implementing the site structure and logic
- Working with conditionals
- Dealing with POST requests
- Sanitizing user inputs and handling form errors