Installing EJS
Getting EJS set up is as easy as installing any npm package. Just run this in your project directory:
npm install ejs
That's it. EJS is now ready to use in your project. No complicated configuration needed.
Basic Rendering
Let's see how to render a template. First, require EJS in your JavaScript file:
const ejs = require('ejs');
Now you can use ejs.render() to turn a string template into HTML:
const template = 'Hello, <%= name %>!
';
const html = ejs.render(template, { name: 'World' });
console.log(html); // Hello, World!
See how easy that is? You pass the template as a string and an object with your data.
Rendering from Files
In real projects, you won't write templates as strings. You'll have them in files. Use ejs.renderFile() for that:
ejs.renderFile('views/home.ejs', { name: 'World' }, (err, html) => {
if (err) console.error(err);
else console.log(html);
});
This reads the file, processes it, and gives you the final HTML. The callback makes it async-friendly.
Try it Yourself →Using EJS with Express
Most people use EJS with Express. Setting it up is straightforward:
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('home', { name: 'World' });
});
Once you set the view engine, Express knows to look for .ejs files in your views folder. Then you just call res.render() with the template name and data.
That's the whole setup. Ready to start building dynamic pages.