EcmaScript 6 : Template literals -- Words (717)


In ES6 ,template literals or as previously known template strings are a way to create strings which can have JavaScript expressions inside ,If you are a JavaScript developer you can imagine how much useful things you can achieve using template strings .

You can create a template literal using back ticks

let str = `This is a template literal in ES6 `;

Template literals have many nice features .

Easy Multiline strings without escaping

You can easily write string variables with multi-line support without using the escape and new line operators .

You can simply write this

const html = `
        <p>Hello template literals </p>

I personally like to use template strings for multi-line support when I'm embedding other languages such as HTML markup or SQL queries inside JavaScript code .In this case you can have nice formatting of the text just like if you are using HTML or SQL in their own source files .

This is very useful for formatting strings of text inside JavaScript code but Template literals can do more than that .You can embed JavaScript expressions inside them and have them evaluated without further actions .

String interpolation and embedded expressions

For example ,I can simply define a JavaScript object or just a simple variable and use it inside a string (Interpolation)

const profile = {
    username: 'mrnerd',
    email: 'Web Developer',
    country: 'Earth'

const html = `
<div class="profile">
    <p >${}</p>
    <p >${}</p>

So as you can see ,with the ${} interpolation operator we can reference any JavaScript variable or even an expression without using concatenation .

Now lets take a more advanced example .If you are familiar with server side or client side template engines or frameworks such as Handlebars ,Jinja or Angular you probably have used constructs such as ,for each or ngFor loops which allow you to iterate over a bunch of items inside templates .Thanks to ES6 template literals you can Now do that using plain JavaScript .

Lets take an array of profiles

const profiles = [
    {username: 'mrnerd',email: 'Web Developer',country: 'Earth'},
    {username: 'ahnerd',email: 'Web Designer',country: 'Earth'},
    {username: 'aknerd',email: 'Web entrepreneur',country: 'Earth'},

Now lets create a template string which iterate over this array to create an HTML list of profiles .

const html = `
<ul class="profiles">
    ${ => 
            `<li> ${profile.username} </li>`
    ).join(' ') }

As we can embed JavaScript expressions in template literals ,we have used a map method on the profiles array which returns an array of strings


Then we use join(' ') to get rid of the array comma ,to finally get

<ul class="profiles">
    <li> mrnerd </li> <li> ahnerd </li> <li> aknerd </li>

String tags

Again if you are familiar with template engines you would know about tags but if you don't ,they are simply a special kind of functions which can be used to preprocess and transform strings for some purpose like ,for example

Better formatting .

Escaping .

Localization depending on your user location .

Adding currencies .

etc .

You can simply tag a template by placing a function name before the string

tag`Hello world by ${me}`;

But make sure you define the tagging function with the same name and a special signature



The function receives the template string parts as arguments ,the first parameter is an array of static parts of the string ,the second parameters are placeholders variables which are embedded on the template string .You can use the tag parameters to decide how you are template string will be transformed .

The previous tag will be called as

tag(["Hello" , "world"],me);


Template literals introduce powerful features to JavaScript such as multiline strings support,string and expression interpolation and tagged templates . You can use these features to build powerful code constructs which mimic things we used to find in template engines and web frameworks ,you can also use them to create own Domain Specific Languages or DSLs .

mrnerd is a Web Entrepreneur & Developer, Digital Marketer and a Passionate Blogger. He writes about software and website development,money making tips and SEO etc.. He is a tech addict and a computer geek with a lot of hobbies.