Last active
May 17, 2022 00:12
-
-
Save mauriciomassaia/8bce634b08d7166bd919138457b05c83 to your computer and use it in GitHub Desktop.
Render HTML template and replace items
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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