Search code examples
javascriptjsonecmascript-6template-strings

Load and replaces variables in template strings loaded from a file


I would like to use ES6 template strings as templates for the translations in my Node.js application.

I have a JSON file en_GB.json like this:

{
  "app.template": "This is ${foo} I ${bar}",
  "app.foo": "bar"
}

In Node I do this:

const translations = require('./en_GB.json')
const foo = 'what'
const bar = 'want'

console.log(translations['app.template']) // Outputs This is ${foo} I ${bar}

What I want to output is "This is what I want'

Is this possible without using a helper function?


Solution

  • Will this work?

    https://www.npmjs.com/package/stringinject

    https://github.com/tjcafferkey/stringinject

    var string = stringInject("This is a {0} string for {1}", ["test", "stringInject"]);
    
    // This is a test string for stringInject