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:
npm install pug
Then, when initializing your Express app, set Pug as the view engine:
const express = require('express')
const app = express()
app.set('view engine', 'pug')
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:
app.get('/about', (req, res) => {
res.render('about')
})
The template itself would be written in views/about.pug
:
p Hello from Flavio
Variables can be interpolated into the template by passing them as an object when rendering:
app.get('/about', (req, res) => {
res.render('about', { name: 'Flavio' })
})
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:
Hello from {{name}}
To use Handlebars as the view engine, add the following code to your Express configuration:
const express = require('express')
const app = express()
const hbs = require('hbs')
app.set('view engine', 'hbs')
app.set('views', path.join(__dirname, 'views'))
app.get('/about', (req, res) => {
res.render('about', { name: 'Flavio' })
})
app.listen(3000, () => console.log('Server ready'))
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:
const express = require('express')
const app = express()
app.set('view engine', 'jsx')
app.engine('jsx', require('express-react-views').createEngine())
app.get('/about', (req, res) => {
res.render('about', { name: 'Flavio' })
})
app.listen(3000, () => console.log('Server ready'))
Create an about.jsx
file in the views/
folder, which will contain your React component:
const React = require('react')
class HelloMessage extends React.Component {
render() {
return <div>Hello from {this.props.name}</div>
}
}
module.exports = HelloMessage
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.