Skip to content

Instantly share code, notes, and snippets.

@jeffmcmahan
Created April 25, 2017 21:12
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 jeffmcmahan/51dd19abcc3b0f8f4b301f71a0f12323 to your computer and use it in GitHub Desktop.
Save jeffmcmahan/51dd19abcc3b0f8f4b301f71a0f12323 to your computer and use it in GitHub Desktop.
HTML template tag
'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