Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Created August 6, 2020 14:50
Show Gist options
  • Save tomhodgins/45b8b86eaecbe502cae4caf40b6f1129 to your computer and use it in GitHub Desktop.
Save tomhodgins/45b8b86eaecbe502cae4caf40b6f1129 to your computer and use it in GitHub Desktop.
Going from a basic HTML function to a tagged template string, to a custom templating solution in three easy steps!
function html(string = '') {
return document.implementation
.createHTMLDocument()
.createRange()
.createContextualFragment(string)
}
/*
A JavaScript function that takes a string of HTML syntax, parses it as HTML and returns a Document Fragment containing all parsed nodes.
*/
console.log(
html(
'The time is <b>'
+ new Date().toLocaleDateString('en-CA', {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'})
+ '</b>'
)
)
function html(strings, ...expressions) {
return document.implementation
.createHTMLDocument()
.createRange()
.createContextualFragment(
strings.reduce((output, string, index) =>
output + expressions[index - 1] + string
)
)
}
/*
A tagged template function that takes a template string of HTML syntax, optionally with JavaScript values and logic interpolated into it using ${}, and returns a Document Fragment containing the parsed HTML DOM objects
*/
html`The time is <b>${
new Date().toLocaleDateString('en-CA', {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'})
}</b>`
function html(strings, ...expressions) {
function customStringify(object) {
// Support custom stringification by type of value being interpolated
if (object instanceof Date) {
return object.toLocaleDateString('en-CA', {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'})
}
return object
}
return document.implementation
.createHTMLDocument()
.createRange()
.createContextualFragment(
strings.reduce((output, string, index) =>
output + customStringify(expressions[index - 1]) + string
)
)
}
/*
A tagged template function that has custom stringification support for different types of data being interpolated into it. You can support as much or as little as you want.
*/
html`The time is <b>${new Date()}</b>`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment