Skip to content

Instantly share code, notes, and snippets.

@mauriciomassaia
Last active May 17, 2022 00:12
Show Gist options
  • Save mauriciomassaia/8bce634b08d7166bd919138457b05c83 to your computer and use it in GitHub Desktop.
Save mauriciomassaia/8bce634b08d7166bd919138457b05c83 to your computer and use it in GitHub Desktop.
Render HTML template and replace items
import { renderTemplate } from './html-utils.ts'
const tpl = `
<div class="item">
<img class="tick-icon" src="./images/icons/tick.png" />
<span>{text}</span>
</div>`
const el = renderTemplate(tpl, { text: 'Hello world' }) as HTMLDivElement
document.body.appendChild(el)
export const renderTemplate = (template: string, replaceItems: any | undefined = undefined): Element => {
let tpl = template
if (replaceItems !== undefined) {
Object.keys(replaceItems).forEach(key => {
tpl = tpl.replaceAll(`{${key}}`, replaceItems[key])
})
}
return new window.DOMParser().parseFromString(tpl, 'text/html').body.children[0]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment