Created
April 28, 2017 16:50
-
-
Save HoverBaum/27408a16d57f2d32d413414cc781dfba to your computer and use it in GitHub Desktop.
Illustrating JS template string for HTML templating.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const numbers = [1, 2, 3, 4] | |
const list = html` | |
<ul> | |
${numbers.map(number => `<li>${number}</li>`)} | |
</ul>` | |
/* | |
At this point we have: | |
<ul> | |
<li>1</li><li>2</li><li>3</li><li>4</li> | |
</ul> | |
Now let us put that into something bigger. | |
*/ | |
const wrappedList = html` | |
<div> | |
<h1>AWESOME STUFF</h1> | |
${list} | |
<div> | |
` | |
/* | |
Now we have: | |
<div> | |
<h1>AWESOME STUFF</h1> | |
<ul> | |
<li>1</li><li>2</li><li>3</li><li>4</li> | |
</ul> | |
<div> | |
*/ | |
// Inspired by: | |
// http://www.2ality.com/2015/01/template-strings-html.html | |
const html = (literalSections, ...substs) => { | |
let raw = literalSections.raw | |
let result = '' | |
substs.forEach((subst, i) => { | |
let lit = raw[i] | |
if (Array.isArray(subst)) { | |
subst = subst.join('') | |
} | |
if (lit.endsWith('$')) { | |
subst = htmlEscape(subst) | |
lit = lit.slice(0, -1) | |
} | |
result += lit | |
result += subst | |
}) | |
result += raw[raw.length - 1] | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment