导入节点js模板文字的文本json

时间:2017-01-20 00:50:08

标签: javascript node.js

对于我的节点js项目,我通常有一个text.json文件并且需要它,而不是在我的代码中有静态文本。类似下面的内容

JSON文件

{
  "greet":"Hello world"
}


var text = require('./text.json');
var greet = text.greet

我在弄清楚如何使用模板文字方面遇到了一些麻烦?

2 个答案:

答案 0 :(得分:1)

我经常使用一个非常小的模板助手库(tim - https://github.com/premasagar/tim),它可以用来完成这个:

Error : .onLoad failed in loadNamespace() for 'RevoUtilsMath', details:
  call: NULL
  error: To use RevoUtilsMath you must first install the MKL Math Library.
Visit http://mran.revolutionanalytics.com/download.
If you have previously installed the MKL Math Library,
remove it using Add/Remove Programs, then re-install.
Error: package or namespace load failed for 'RevoUtilsMath'
Execution halted

相关的JSFiddle:

https://jsfiddle.net/rtresjqv/

或者,您可以将字符串转换为函数,然后传入参数:

//in my json file
var strings = {
   'Hello': 'Hello {{name}}!',
   'Goodbye': 'Goodbye {{name}}!'
};

//in my app
var tim = require('tim'); //templating library
var strings = require('./strings.json');

//replace
console.log(tim(strings.Hello,{name:'Fred'}));

小提琴: https://jsfiddle.net/t6ta0576/

答案 1 :(得分:0)

我知道这是一个老问题,但是我只是想出同样的事情,而且..是的,有一些节点模块可以帮助完成此任务,但是,这并不复杂,所以我只是制定了自己的解决方案< / p>

function injectVariables( replacements, input ) {
    const entries = Object.entries(replacements)
    const result = entries.reduce( (output, entry) => {
        const [key, value] = entry
        const regex = new RegExp( `\\$\{${key}\}`, 'g')
    return output.replace( regex, value )
    }, input )
    return result
} 


const template = 'Hello my name is ${name} and I like ${language}'
const inputs = { name: 'David', language: 'JavaScript' }
const replaced = injectVariables(inputs, template) 
console.log(replaced)

因此,在此方法中,它需要一个输入字符串和一个对象,其中键是字符串中的变量名,而值是您猜到的值。

它使用Object.entries创建一个值数组,然后在所有条目上运行reduce,以在使用时保持字符串的更新版本。在每次迭代中,它都会生成一个正则表达式来匹配变量表达式,并用传递的值替换该值。

这尤其不会浏览嵌套对象(我不需要),但是例如,如果您的字符串中包含${name.last},因为对象键可以是字符串,则您的输入变量可以是{{ 1}},它应该可以工作。

希望这对其他人有帮助。

相关问题