Skip to content

Instantly share code, notes, and snippets.

@ifyoumakeit
Last active March 19, 2018 17:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ifyoumakeit/f866204e208ae45b9ae6e69b876e7530 to your computer and use it in GitHub Desktop.
Save ifyoumakeit/f866204e208ae45b9ae6e69b876e7530 to your computer and use it in GitHub Desktop.
Quick JS templating with string template literals
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