7/6/19

Tagged Template Literals

Ok, everybody heard about "backticks" ES6 feature...


 const hero = 'Splinter'
 console.log(`My name is ${hero}`); 
// will print "My name is Splinter"

But recently I stumble upon following code I could not understand:

import { css, cx } from 'emotion'

const color = 'white'

render(
  <div
    className={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
      &:hover {
        color: ${color};
      }
    `}
  >
    Hover to change color.
  </div>
)

What is this strange syntax?

Tagged Template Literals

Well it appears you can tag a template with function
Like this:

 const hero = 'Splinter';

 const printHero = html`My name is ${hero}`;
 // here is the function:
 function html(strings, ...values) {
   let str = '';
   strings.forEach((string, i) => {
       str += `${string} ${values[i] || ''}`;
   });
   return str;
 }

/*
printHero will print:
"My name is  <span class='hl'>Splinter</span> <span class='hl'></span>"
*/

Using tagged template gives you ability to control the way the template is parsed.

No comments:

Post a Comment

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...