Created
April 25, 2017 21:12
-
-
Save jeffmcmahan/51dd19abcc3b0f8f4b301f71a0f12323 to your computer and use it in GitHub Desktop.
HTML template tag
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
'use strict' | |
/** | |
* Print null/undefined and arrays to strings sensibly. | |
* @param {*} val | |
* @param {String} str | |
* @return {String} | |
*/ | |
function htmlValue(val, str) { | |
if (val === null || typeof val === 'undefined') return '' | |
if (val instanceof Array) return val.map(htmlValue).join(' ') | |
if (typeof val === 'object') return `<pre>${JSON.stringify(val, null, 2)}</pre>` | |
return val.toString() | |
} | |
/** | |
* Template tag function for interpolating variables into HTML templates. | |
* @param {String[]} strings | |
* @param {...*} values | |
* @return {String} | |
*/ | |
module.exports = function html(strings, ...values) { | |
let output = '' | |
strings.forEach((str, i) => { | |
if (i >= values.length) output += str | |
else output += str + htmlValue(values[i], str) | |
}) | |
return output.trim() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment