Q1. What are templating engines in Express?
Templating engines allow you to generate dynamic HTML on the server.
They combine templates with data to produce HTML.
Express supports many engines like EJS, Pug, Handlebars.
They help in creating server-rendered applications.
They combine templates with data to produce HTML.
Express supports many engines like EJS, Pug, Handlebars.
They help in creating server-rendered applications.
Q2. How do you set up EJS with Express?
Install EJS:
Set the view engine:
By default, Express looks for views in a 'views' folder.
Create
In routes, use
npm install ejs.Set the view engine:
app.set('view engine', 'ejs');By default, Express looks for views in a 'views' folder.
Create
.ejs files there.In routes, use
res.render('filename', { data }) to render.Q3. What is the difference between EJS and Pug?
EJS uses HTML-like syntax with embedded JavaScript (
Pug uses indentation-based syntax with no closing tags, which is more concise but has a learning curve.
EJS is more popular for those familiar with HTML.
<%= %>). It's easy for beginners.Pug uses indentation-based syntax with no closing tags, which is more concise but has a learning curve.
EJS is more popular for those familiar with HTML.
Q4. How do you pass data to a template?
Use the second argument of
In EJS, you access these variables directly:
In Pug, you use
You can pass any JavaScript object.
res.render(): res.render('profile', { name: 'John', age: 30 }).In EJS, you access these variables directly:
<%= name %>.In Pug, you use
#{name} or = name.You can pass any JavaScript object.
Q5. Can you use partials or layouts with templating engines?
Yes, most engines support reusability.
EJS has includes:
Pug has
This helps in creating consistent layouts (headers, footers) across pages without repeating code.
EJS has includes:
<%- include('header') %>.Pug has
extends and blocks.This helps in creating consistent layouts (headers, footers) across pages without repeating code.
