How to use template engines with Express
· Category: Node.js
Short answer
Set the view engine and views directory with app.set(), then use res.render() to generate HTML from templates.
Steps
- Install a template engine like EJS:
npm install ejs. - Configure Express:
app.set('view engine', 'ejs');andapp.set('views', './views');. - Create a template file
views/index.ejswith HTML and embedded JavaScript tags. - Render the template in a route:
app.get('/', (req, res) => res.render('index', { title: 'Home' }));. - Pass data as the second argument to
res.render().
Tips
- EJS uses
<% %>for control flow and<%= %>for outputting values safely escaped. - You can use
express-handlebarsif you prefer logicless templates with helpers.
Common issues
- Express cannot find templates if the
viewsdirectory path is incorrect relative to the working directory. - Syntax errors in template files often produce cryptic stack traces pointing to the engine rather than the template.