5 ms·
Show HN: Simple dynamic templating in JS
How do you guys deal with this scenario?
const renderTemplate = (template, obj) => {
const args = Object.keys(obj)
const body = `return (\`${template}\`)`
const renderFunc = new Function(...args.concat([body]))
return renderFunc(...Object.values(obj))
}
const dynamicallyLoadedTemplate = '${a} and ${b}'
console.log(
renderTemplate(dynamicallyLoadedTemplate, {
'a': '1',
'b': 2
})
)
Is this elegant enough?
- fiatjaf 8y agoeval? You can't say that's elegant.
- sotaan 8y agoIt's how `vue-template-compiler` works to transform a template into render functions. checkout here: https://github.com/vuejs/vue/blob/dev/packages/vue-template-compiler/browser.js#L4512 https://github.com/vuejs/vue/blob/dev/packages/vue-template-... also checkout last 'state of Vue.js' on YT where the creator talks about it ;)
- jgalvez 8y agoAwesome, thanks for the pointer.