News for hackers. Stuff that matters.

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?
( 5 comments | 3 points | on HN )
Re:Show HN: Simple dynamic templating in JS by sotaan on Monday April 30, 2018 @04:50AM (#16956895)
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-...

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

Re:Show HN: Simple dynamic templating in JS by jgalvez on Monday April 30, 2018 @06:55AM (#16957486)
Awesome, thanks for the pointer.
Re:Show HN: Simple dynamic templating in JS by fiatjaf on Sunday April 29, 2018 @10:06PM (#16955186)
eval? You can't say that's elegant.
Re:Show HN: Simple dynamic templating in JS by jgalvez on Monday April 30, 2018 @08:28AM (#16957977)
Also, it runs for function definition only. It's not used for running code on-the-fly.
Re:Show HN: Simple dynamic templating in JS by sotaan on Monday April 30, 2018 @04:52AM (#16956901)
new Function(...) isn't equivalent to an eval