[英]Is it possible to use tagged template literals with template literals saved as constants?
我正在開發一個有多種語言的應用程序。 我們沒有使用像“i18n”這樣的包,而是——因為字符串文字的數量不是很大——使用這樣的系統:
// constants
const GREETING = 'greeting'
// es.js -- a language object
const aLanguageObject = {[GREETING] : '¿Cómo estás?'}
// helper function
const getText(selector) = currentLanguageObject[selector]
// usage file
const greetingPhrase = getText(GREETING);
其中currentLanguageObject
是es.js
、 en.js
等之一,即已經定義的languageObject
之一(我們根據process.env
值選擇)
我們希望能夠使用標記的模板文字將值插入到這些保存為常量的模板文字中。
我試圖讓標記模板文字與我們的系統一起工作,如下所示:
// en.js
const aLanguageObject = {[CONFIRM_NUMBER] : `is the number ${0} correct?`}
and then use tagged templates like this
const theNumber = 12;
const myTag = (strings, numberExp) => `${strings[0]}${theNumber}${strings[1]}`;
const numberConfirmString = myTag`${getText(CONFIRM_NUMBER)})`;
但 numberConfirmString 是undefined
。
有沒有辦法“填寫”保存為常量的模板文字? 非常感謝任何幫助!
語法:
const obj = {[key] = value}
應該:
const obj = {[key]: value}
否則,會出現 SyntaxError。
除此之外,我認為這樣的事情應該有效:
function generaTemplate (strings, ...keys) {
return function(data) {
let temp = strings.slice();
keys.forEach((key, i) => {
temp[i] = temp[i] + data[key];
});
return temp.join('');
}
}
const userTpl = user => generaTemplate`<article>
<p>Name: ${'name'}</p>
<p>Age: ${'age'}</p>
</article>`(user);
const users = [{
name: 'Eric',
age: '10'
}, {
name: 'Rob',
age: '20'
}];
const usersList = users.reduce((acc, user) => {
return acc + userTpl(user);
}, '');
console.log(usersList);
它返回這個:
<article>
<p>Name: Eric</p>
<p>Age: 10</p>
</article><article>
<p>Name: Rob</p>
<p>Age: 20</p>
</article>
作為替代方案,您還可以使用:
const welcome = param => `Hello, ${param}`;
console.log(welcome('world'));
輸出:
你好,世界
檢查這個: 推遲執行 ES6 模板文字
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.