我正在尝试将模板文字与Lodash的_.template()
结合使用,以便根据另一个确定打开/关闭且对我不起作用的函数的响应,从JSON文件中选择一条消息。
流量:
open
对象返回close
或opencloseResponse.openclose
(假设正在工作,并且未在下面的代码段中显示)_.template()
,我将messages.open
或messages.close
的用户名设为first_name
messages.json
{
"messages": {
"open": "Hello ${ first_name }! We are open!",
"closed": "Hello ${ first_name }! We are closed!"
}
}
app.js
const _ = require('lodash');
const { messages } = require('messages.json');
const sendMessage = _.template(messages.open);
console.log(sendMessage({ first_name: 'Jeremy' }));
output
Hello Jeremy! We are open!
messages.json
{
"messages": {
"open": "Hello ${ first_name }! We are open!",
"closed": "Hello ${ first_name }! We are closed!"
}
}
app.js
const _ = require('lodash');
const { messages } = require('messages.json');
const sendMessage = _.template(`messages.${opencloseResponse.openclose}`);
console.log(sendMessage({ first_name: 'Jeremy' }));
output
messages.open
我希望它缺少一些简单的东西。整天都让我发疯。感谢您的帮助!
答案 0 :(得分:2)
您不需要模板文字。
只需使用方括号[]
表示法即可访问message
属性
const sendMessage = await _.template(messages[opencloseResponse.openclose]);
答案 1 :(得分:2)
Lodash的模板和JavaScript的模板文字完全不同。如果要继续使用这些JSON文件,则不会使用JavaScript的模板文字,而只需使用动态属性访问即可:
const sendMessage = _.template(messages[opencloseResponse.openclose]);
console.log(sendMessage({ first_name: 'Jeremy' }));
如果要使用模板文字,使它们可重复使用的方法是将它们包装在 function 中。例如,您可能有一个messages.json
,而不是messages.js
:
exports.messages = {
"open": (first_name) => `Hello ${ first_name }! We are open!`,
"closed": (first_name) => `Hello ${ first_name }! We are closed!`
};
然后
const messages = require('./messages');
console.log(sendMessage(messages[opencloseResponse.openclose]('Jeremy')));
或者,如果愿意,您可以让函数像Lodash代码一样接受对象:
exports.messages = {
"open": ({first_name}) => `Hello ${ first_name }! We are open!`,
// ^----------^-------------------------------------------------- destructuring
"closed": ({first_name}) => `Hello ${ first_name }! We are closed!`
// ^----------^------------------------------------------------ destructuring
};
然后
const messages = require('./messages');
console.log(sendMessage(messages[opencloseResponse.openclose]({first_name: 'Jeremy'})));