Skip to content

Instantly share code, notes, and snippets.

@HoverBaum
Created April 28, 2017 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HoverBaum/27408a16d57f2d32d413414cc781dfba to your computer and use it in GitHub Desktop.
Save HoverBaum/27408a16d57f2d32d413414cc781dfba to your computer and use it in GitHub Desktop.
Illustrating JS template string for HTML templating.
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