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

  1. Install a template engine like EJS: npm install ejs.
  2. Configure Express: app.set('view engine', 'ejs'); and app.set('views', './views');.
  3. Create a template file views/index.ejs with HTML and embedded JavaScript tags.
  4. Render the template in a route: app.get('/', (req, res) => res.render('index', { title: 'Home' }));.
  5. 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-handlebars if you prefer logicless templates with helpers.

Common issues

  • Express cannot find templates if the views directory 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.