Express Templates: A Guide to Server-Side Template Engines
Express is a powerful framework that can handle server-side template engines, allowing developers to dynamically generate HTML by adding data to views. The default template engine used by Express is Jade, which has now been renamed to Pug due to a trademark issue. While Jade (or Pug 1.0) is still the default in Express for backward compatibility reasons, it’s recommended to use Pug 2.0 or another engine of your choice in new projects.
To use Pug, you first need to install it by running:
1 | npm install pug |
Then, when initializing your Express app, set Pug as the view engine:
1 | const express = require('express') |
With Pug installed and configured, you can start writing your templates in .pug
files. For example, to create an about view that displays the text “Hello from Flavio”, you can define a route in your Express app and render the corresponding template:
1 | app.get('/about', (req, res) => { |
The template itself would be written in views/about.pug
:
1 | p Hello from Flavio |
Variables can be interpolated into the template by passing them as an object when rendering:
1 | app.get('/about', (req, res) => { |
1 | p Hello from #{name} |
For more information on using Pug with Express, refer to the Pug guide.
If you prefer using Handlebars instead of Pug, you can install it by running npm install hbs
. You can then define an about.hbs
template file in the views/
folder:
To use Handlebars as the view engine, add the following code to your Express configuration:
1 | const express = require('express') |
If you want to render a React application server-side, you can use the express-react-views
package. Install it along with React and React DOM by running npm install express-react-views react react-dom
. Once installed, modify your Express configuration as follows:
1 | const express = require('express') |
Create an about.jsx
file in the views/
folder, which will contain your React component:
1 | const React = require('react') |
Although Jade/Pug is the default template engine in Express, it’s recommended to use Pug 2.0 or another engine for new projects. Handlebars and React are also popular choices for server-side rendering in Express.
tags: [“Express”, “Templates”, “Pug”, “Jade”, “Handlebars”, “React”]