How to Set View Engine in Express: Simple Guide
In Express, you set the view engine using
app.set('view engine', 'engineName'), where engineName is the template engine like pug or ejs. This tells Express how to render your views when you call res.render().Syntax
The syntax to set a view engine in Express is simple. You use the app.set() method with two arguments:
- Key:
'view engine'- this tells Express you want to set the template engine. - Value: the name of the template engine as a string, like
'pug','ejs', or'hbs'.
After setting this, Express knows how to process your template files when rendering views.
javascript
app.set('view engine', 'pug');
Example
This example shows how to set up Express with the Pug view engine and render a simple page. It demonstrates setting the view engine, creating a route, and rendering a Pug template.
javascript
import express from 'express'; import path from 'path'; const app = express(); // Set the directory where template files are located app.set('views', path.join(process.cwd(), 'views')); // Set Pug as the view engine app.set('view engine', 'pug'); // Define a route that renders the 'index' template app.get('/', (req, res) => { res.render('index', { title: 'Welcome', message: 'Hello from Express with Pug!' }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
Some common mistakes when setting the view engine in Express include:
- Not installing the template engine package (e.g.,
npm install pug). - Forgetting to set the
viewsdirectory, so Express can't find your templates. - Using the wrong engine name in
app.set('view engine', 'engineName'). - Calling
res.render()with a template name that does not exist.
Always ensure your template engine is installed and your views folder is correctly set.
javascript
/* Wrong way: engine not installed or wrong name */ app.set('view engine', 'pug'); // but pug package not installed /* Right way: install pug and set views folder */ // npm install pug app.set('views', path.join(process.cwd(), 'views')); app.set('view engine', 'pug');
Quick Reference
Here is a quick summary of setting the view engine in Express:
| Step | Description | Example |
|---|---|---|
| 1 | Install the template engine package | npm install pug |
| 2 | Set the views folder (optional, defaults to './views') | app.set('views', path.join(process.cwd(), 'views')) |
| 3 | Set the view engine | app.set('view engine', 'pug') |
| 4 | Render a template in a route | res.render('index', { title: 'My Page' }) |
Key Takeaways
Use app.set('view engine', 'engineName') to tell Express which template engine to use.
Always install the template engine package before setting it in Express.
Set the views directory if your templates are not in the default './views' folder.
Use res.render('templateName') to render templates with the chosen engine.
Check for typos in engine names and template file names to avoid errors.