Skip to content

Instantly share code, notes, and snippets.

@jeffmcmahan
Created Apr 25, 2017
Embed
What would you like to do?
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