Performance: Template partials and layouts
This affects the server-side rendering speed and the size of the HTML sent to the browser, impacting the Largest Contentful Paint (LCP).
app.set('view engine', 'ejs'); // layout.ejs contains common header and footer // page1.ejs and page2.ejs include only page-specific content app.get('/page1', (req, res) => { res.render('page1', { title: 'Page 1' }); }); app.get('/page2', (req, res) => { res.render('page2', { title: 'Page 2' }); });
app.get('/page1', (req, res) => { res.render('page1', { title: 'Page 1' }); }); // page1.ejs contains full HTML including header and footer hardcoded app.get('/page2', (req, res) => { res.render('page2', { title: 'Page 2' }); }); // page2.ejs also repeats full HTML header and footer
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Duplicated full HTML in each template | High (large HTML size) | N/A (server-side) | High (large HTML to parse) | [X] Bad |
| Using partials and layouts for common HTML | Low (smaller HTML size) | N/A (server-side) | Low (smaller HTML to parse) | [OK] Good |
header in an EJS template?<%- include('partialName') %> to include partials with unescaped output.<%- include('header') %> matches the correct syntax with parentheses and quotes around 'header'.app.set('view engine', 'ejs');
// In route handler:
res.render('index', { title: 'Home' });layout.ejs contains:<html> <head><title><%= title %></title></head> <body> <%- body %> </body> </html>
index.ejs has <h1>Welcome</h1>, what will the rendered HTML look like?<%- body %> to insert the rendered content of index.ejs unescaped.<%= title %> becomes 'Home'. The body inserts <h1>Welcome</h1> as HTML.ReferenceError: body is not defined. What is the likely cause?express-ejs-layouts to inject body content.body is undefined, it means the layout engine or middleware that sets body is missing or not configured.Pass the test and this pattern moves unknown