Discussion

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?
3 points jgalvez 8 years ago 5 comments

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton