Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active March 21, 2020 23:53
Show Gist options
  • Save tomhodgins/bd5d9ff27fc16369d36985da9dcf8ba9 to your computer and use it in GitHub Desktop.
Save tomhodgins/bd5d9ff27fc16369d36985da9dcf8ba9 to your computer and use it in GitHub Desktop.
// Tagged template function for parsing a template string as CSS stylesheet
// …you can remove async from this if you replace the dynamic import with:
// import {parse} from 'https://unpkg.com/cssomtools'
async function css(strings, ...things) {
const {parse} = await import('https://unpkg.com/cssomtools')
return parse(
strings.reduce((styles, string, index) => styles + things[index - 1] + string)
)
}
// Tagged template function for parsing a template string as an HTML documentFragment
function html(strings, ...things) {
return document.implementation.createHTMLDocument().createRange().createContextualFragment(
strings.reduce((markup, string, index) => markup + things[index - 1] + string)
)
}
// Tagged template function for parsing a template string as JSON
function json(strings, ...things) {
return JSON.parse(
strings.reduce((json, string, index) => json + things[index - 1] + string)
)
}
// Tagged template function for parsing a template string as a <style> tag client-side in the browser
function style(strings, ...things) {
let tag = document.querySelector('#css-debugging')
if (tag === null) {
tag = document.createElement('style')
tag.id = 'css-debugging'
document.documentElement.append(tag)
}
tag.textContent += strings.reduce(
(css, string, index) => css + things[index - 1] + string
)
}
// Tagged template function for parsing a template string as an XML documentFragment
function xml(strings, ...things) {
return document.implementation.createDocument(null, 'xml').createRange().createContextualFragment(
strings.reduce((markup, string, index) => markup + things[index - 1] + string)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment