Show HN: Simple dynamic templating in JS

3 points by jgalvez ↗ HN
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.4 ms ] story [ 21.6 ms ] thread
eval? You can't say that's elegant.
new Function(...) isn't equivalent to an eval
Also, it runs for function definition only. It's not used for running code on-the-fly.