Show HN: Simple dynamic templating in JS

https://news.ycombinator.com/item?id=16954342
by jgalvez • 8 years ago
3 5 8 years ago

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?

Related Stories

Loading related stories...

Source preview

news.ycombinator.com