Template Literals Templating

What are Template Literals?

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. Template Literals are part of the ES6 specification.

Actually they even contain the basic requirements to use it as a templating language!

Some Examples

First a simple example:

const aValue = 30;
const result = `Embedded expression ${10+10 + aValue}`;

Template literals are strings enclosed by the back-tick (` grave accent) character instead of double or single quotes. Unlike a normal string, a template literal can span multiple lines, eg:

const result = `This
is valid
code`;

Even function calls and nested templates are possible, eg:

const result = `We can have a ternary operation: 
    ${ isTrue(a) 
        ? `it is true-isch: ${a}`
        : `it is false-isch: ${a}` }`;

Use it as template language

Of course it is an ugly hack to use template literals as full template language. It doesn’t prevent you from adding logic directly to the template, so it requires some discipline to keep the templates as clean as possible. This is something templating languages like Handlebars or Mustache enforce.

With some tricks it is possible to have comments, conditional blocks and loops.

Comment:

${'' /* Put comment here! */ }

Conditional block:

${isTrue(a) ? `
Conditional block with expression ${a}
`:''}

Loop:

<ul>
${orders.map(order => `
    <li>${order.title}</li>
`).join('')}
</ul>

Advanced

A code snippet that provides us full server side templating support in Node:

const fs = require('fs');
const vm = require('vm');

const template = fs.readFileSync('template.js');
const script = new vm.Script(template);

const html = script.runInNewContext({
orders: [{name:'One'}, {name:'Two'}]
});

Resources

Leave a Reply

Your email address will not be published.