APIs with Express · Chapter 11 of 29
Templates
By the end of this chapter you can turn data into HTML pages with a template engine you wrote yourself, safely escaped, with loops and a shared layout, and render them with res.render. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Middleware
- 5 tasks
- Express
- In the all labs plan
The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.
Why you need this
Partner cafés read JSON, but Ravi's kitchen tablet shows web pages. He wants a page per order: who ordered, what to make, and the customer's note. Anjali wants the menu as a page too, with the same header and footer on every page.
With what you know, every route would glue HTML together from strings. The header gets copied into each one, and sooner or later a customer's note goes into the page as it was typed, <script> tags and all.
What you build: 5 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
renderTemplate: fill {{placeholders}}, dotted paths included
Export renderTemplate(source, locals), which returns source with every {{name}} replaced by that value from locals. Spaces inside the braces are allowed ({{ name }}), and a dotted path follows nested objects: {{order.customer.name}} with { order: { id: 7, customer: { name: 'Asha' } } } gives Asha.
0 is a value and shows as 0. A missing value, null, and a path through something missing ({{order.nope.deeper}}) all give the empty string. Text with no tags comes back unchanged.
- Task 2 · interview question
Interview: escape every value, so a note cannot inject HTML
Finish escapeHtml(text), which replaces & < > " ' with & < > " ', and make renderTemplate escape every {{value}}: a note of <script>alert("free chai")</script> comes out as <script>alert("free chai")</script>, and an attribute value of " onerror="steal() cannot break out of its quotes.
Triple braces, {{{body}}}, insert the value without escaping: { body: '<h2>Menu</h2>' } gives <h2>Menu</h2>.
Text from the data is never read as a template: a note of {{secret}} stays {{secret}}, even when locals has a secret.
- Task 3
renderTemplate: repeat {{#each}} blocks
Make renderTemplate repeat {{#each list}}...{{/each}}: the inside is rendered once per item of the list, joined with nothing between, where the item's fields and the outer locals are both visible and values are escaped as usual.
{ items: [{ name: 'Masala chai', price: 40 }, { name: 'Cutting chai', price: 25 }] } with <ul>{{#each items}}<li>{{name}} {{price}}</li>{{/each}}</ul> gives <ul><li>Masala chai 40</li><li>Cutting chai 25</li></ul>. The list may be a dotted path ({{#each order.items}}). An empty or missing list renders nothing, and the text around it stays: [{{#each nothing}}<li>x</li>{{/each}}] {{after}} gives [] done.
- Task 4
tapriEngine and createApp: render the menu view
Finish tapriEngine(filePath, options, callback): read the file, render it with renderTemplate and the options as locals, then call callback(null, html), or callback(err) when something fails.
In createApp({ viewsDir }), register tapriEngine for .tapri files, make viewsDir the views folder and tapri the default view engine, and set app.locals.cafe to 'Tapri'. GET /menu (already written) renders the check's menu.tapri, <h1>{{cafe}} menu</h1><ul>{{#each items}}<li>{{name}}: Rs {{price}}</li>{{/each}}</ul>, and answers 200 as text/html: '<h1>Tapri menu</h1><ul><li>Masala chai: Rs 40</li><li>Cutting chai: Rs 25</li><li>Bun maska: Rs 35</li></ul>'. The views come from the folder createApp was given: a menu.tapri of {{cafe}} has {{items.length}} items gives 'Tapri has 3 items'.
Tasks 1 to 3 must be done first: the menu view uses a loop.
- Task 5
tapriEngine: wrap the order page in a layout
When options.layout names a view (GET /orders/:id passes layout: 'layout'), tapriEngine renders the page first, then renders that view (layout.tapri, from the same folder as the page) with the same options plus body set to the page's HTML, and calls back with the result.
The check's order.tapri is <h2>Order #{{order.id}} for {{order.customer}}</h2><ul>{{#each order.items}}<li>{{qty}} x {{name}}</li>{{/each}}</ul><p class="note">{{order.note}}</p>, and its layout.tapri is <!doctype html><title>{{title}} | {{cafe}}</title><main>{{{body}}}</main><footer>Indiranagar</footer>.
GET /orders/2 answers 200 as text/html, exactly: '<!doctype html><title>Order #2 | Tapri</title><main><h2>Order #2 for Rohan & Sons</h2><ul><li>3 x Cutting chai</li><li>1 x Bun maska</li></ul><p class="note"><script>alert("free chai")</script></p></main><footer>Indiranagar</footer>'. GET /orders/1 has the title Order #1 | Tapri and the note Less sugar. An unknown order still answers 404 with the text No such order.
What you will learn
- res.render and app.engine: how Express finds a template file and hands it to an engine.
- Filling placeholders in one pass: one replace with a callback.
- Escaping: why every value from the data is escaped by default.
- Loops and layouts: repeating part of a template, and wrapping a page in a shared frame.
More in Middleware
Build "Templates" yourself
Partner cafés want Tapri’s menu online by Friday: you build its API. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.