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 functionLike 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