23.3. A template engine with loops and conditions
Topics
This question is in
23. Text processing and interpretersA list page needs more than holes to fill: "show the list, or No results when it is empty", "mark the current item", "a group heading, then its items". Template engines add blocks for that: a condition and a loop, which can sit inside each other to any depth. Blocks turn a flat string into a tree, and a loop brings a new question: inside a loop over users, does name mean the user's name or the page's?
Write compile(template) in template.js. It reads the template once and returns a function that renders it with data. Every value is HTML-escaped unless the template asks for raw output.
Signature
function compile(template) // returns (data) => stringThe tags:
| Tag | Meaning |
|---|---|
{{ path }} | the value at path, HTML-escaped |
{{{ path }}} | the value at path, not escaped (for HTML you already trust) |
{{#if path}} … {{else}} … {{/if}} | the first part when the value is true, else the second part ({{else}} is optional) |
{{#each path}} … {{else}} … {{/each}} | the first part once per item of an array; the {{else}} part when there is nothing to loop over |
{{ this }}, {{ this.name }} | the current item of the innermost #each (outside any loop: the data) |
{{ @index }} | the position of the current item, from 0 |
A path is names of letters, digits, _ and $ joined by dots (user.name, items.0), or @index. Spaces just inside the braces are ignored. The word else alone in a tag is always the {{else}} tag.
Requirements
- Text outside tags is copied unchanged. A missing value,
nullorundefinedrenders as""; any other value asString(value). {{ }}output is escaped:&to&(first),<to<,>to>,"to",'to'.{{{ }}}output is not.#ifuses JavaScript truthiness, except that an empty array counts as false.#eachloops over arrays only. An empty array, a missing value, or anything that is not an array renders the{{else}}part, or nothing.- Inside
#each, a path whose first name is an own property of the current item reads from the item. Otherwise the lookup tries the next loop out, and so on, up to the data. Only own properties ever count. #ifdoes not change the scope;{{ @index }}inside it is the index of the loop around it.- Blocks nest to any depth, including inside
{{else}}parts, and each closing tag closes the innermost open block. compilethrows aSyntaxError, before any rendering, for: a tag without its closing braces, an invalid path, a block that is never closed, a closing tag that does not match the innermost open block, a closing tag with nothing open, an{{else}}outside a block or a second{{else}}in one block, and any block name other thanifandeach.- One compiled function can render many data objects; the data is never changed, and values are never parsed as templates.
Examples
const list = compile(
"{{#each users}}<li>{{@index}}. {{name}}{{#if admin}} (admin){{/if}}</li>{{else}}<li>No users</li>{{/each}}"
);
list({ users: [{ name: "Asha", admin: true }, { name: "<b>Ben</b>" }] });
// "<li>0. Asha (admin)</li><li>1. <b>Ben</b></li>"
list({ users: [] });
// "<li>No users</li>"compile("{{#each groups}}{{name}}:{{#each items}}{{this}}{{/each}};{{/each}}")({
groups: [{ name: "g", items: ["1", "2"] }, { name: "h", items: [] }],
});
// "g:12;h:;"compile("{{#each tags}}{{this}}{{sep}}{{/each}}")({ tags: ["a", "b"], sep: "," });
// "a,b,": the items are strings, so sep comes from the data
compile("{{#if a}}{{/each}}"); // throws SyntaxErrorEnvironment
- Plain JavaScript in a browser page; the tests call the global
compilefromtemplate.js. - Helpers, partials, comments, whitespace control and other block names are not part of this problem. Problem 23.2 is the version without blocks.
- Any built-in is allowed. A single regular expression cannot pair nested blocks correctly; the tests nest blocks of the same kind.
Hints
- What if the work is split in two: a list of tokens first (text, value, open, else, close), then a tree built from them?
- When a block opens, where should the next tokens go until it closes? What data structure remembers the blocks that are still open?
- Inside two loops, a name can live on the inner item, the outer item or the data. How would you keep all three, in order?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it