Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Show HN: Simple dynamic templating in JS
3 points by jgalvez on April 29, 2018 | hide | past | favorite | 5 comments
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?


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 ;)


Awesome, thanks for the pointer.


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


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


new Function(...) isn't equivalent to an eval




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: