Last active
March 19, 2018 17:23
-
-
Save ifyoumakeit/f866204e208ae45b9ae6e69b876e7530 to your computer and use it in GitHub Desktop.
Quick JS templating with string template literals
This file contains 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 resolveExpression = exp => { | |
const resolved = typeof exp === "function" ? exp() : exp; | |
return Array.isArray(resolved) | |
? resolved.join("") | |
: typeof resolved !== "undefined" ? resolved : ""; | |
}; | |
const html = (strings, ...exps) => { | |
return strings.reduce((acc, str, i) => { | |
return `${acc}${resolveExpression(exps[i - 1])}${str}`; | |
}, ""); | |
}; | |
html` | |
<foo> | |
${[1, 2, 3].map(i => { | |
return html`<div>${i}</div>`; | |
})} | |
</foo> | |
`; | |
/** | |
* <foo> | |
* <div>1</div> | |
* <div>2</div> | |
* <div>3</div> | |
* </foo> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment