EJS (Embedded JavaScript or perhaps Effective or Elegant or Easy JavaScript) is a templating language that lets you generate HTML markup using JavaScript. EJS enables server-side rendering of HTML and is available as a Node module, making it a popular choice for managing templates in server-side environments.
Setup
Setting up a Node.js application with EJS requires these steps:
- Installing EJS (via NPM)
npm i ejs
- Adding the following startup code (code shown below on the index.js file of an Express-based Node application)
const express = require('express');
const app = express();
const path = require('path')
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views')) // Specifies where EJS templates are located relative to index.js
Rendering EJS
From an Express-based Node application, rendering an EJS template is as easy as the following line of code
app.get('/=', (req, res) => {
res.render('index', {user: userDetails})
})
This code looks for an index.ejs file in the views directory and renders it on screen. The index.ejs template also receives a user object (passed as the second parameter).
Passing Variable to a Partial
To pass a variable from an EJS template to a partial, you can either pass the variable as-is or use a template string with string interpolation, as shown below
<%- include('partials/header', {title: user }) %> // Passing incoming variable as-is
<%- include('partials/header', {title: `User Details - ${user.name}` }) %> // Templated string