
Show HN: Simple dynamic templating in JS - jgalvez
How do you guys deal with this scenario?<p><pre><code>  const renderTemplate = (template, obj) =&gt; {
    const args = Object.keys(obj)
    const body = `return (\`${template}\`)`
    const renderFunc = new Function(...args.concat([body]))
    return renderFunc(...Object.values(obj))
  }
  const dynamicallyLoadedTemplate = &#x27;${a} and ${b}&#x27;
  console.log(
    renderTemplate(dynamicallyLoadedTemplate, {
      &#x27;a&#x27;: &#x27;1&#x27;,
      &#x27;b&#x27;: 2
    })
  )
</code></pre>
Is this elegant enough?
======
sotaan
It'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-...](https://github.com/vuejs/vue/blob/dev/packages/vue-template-
compiler/browser.js#L4512)

also checkout last 'state of Vue.js' on YT where the creator talks about it ;)

~~~
jgalvez
Awesome, thanks for the pointer.

------
fiatjaf
eval? You can't say that's elegant.

~~~
jgalvez
Also, it runs for function definition only. It's not used for running code on-
the-fly.

