【问题标题】:Load and replaces variables in template strings loaded from a file [duplicate]加载和替换从文件加载的模板字符串中的变量[重复]
【发布时间】:2017-12-24 14:22:35
【问题描述】:

我想在我的 Node.js 应用程序中使用 ES6 模板字符串作为翻译模板。

我有一个 JSON 文件 en_GB.json 像这样:

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

在节点中我这样做:

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

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

我想要输出的是“这就是我想要的”

不使用辅助函数可以吗?

【问题讨论】:

    标签: javascript json ecmascript-6 template-strings


    【解决方案1】:

    这行得通吗?

    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 
    

    【讨论】:

    • 不,我需要能够按名称指定变量。我也在寻找一种本地方式来做到这一点。
    • 我已经更新了我的 NPM 包以允许这样做。这是你要找的吗? npmjs.com/package/stringinject
    猜你喜欢
    • 2017-01-15
    • 2016-04-10
    • 1970-01-01
    • 2011-01-11
    • 2011-12-23
    • 2013-01-29
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    相关资源
    最近更新 更多