作者oopFoo (3d)
看板Soft_Job
標題[心得] 一行的Javascript template engine
時間Tue Sep 4 15:07:04 2018
https://stackoverflow.com/questions/30003353/can-es6-template-literals-be-substituted-at-runtime-or-reused
function fillTemplate(templateString,templateVars) {
return new Function(`return \`${templateString}\`;`).call(templateVars);
}
因為需要做多國語言(前端做),找類似printf功能來置換value。
有看到,但都不滿意,因為想用es6 template literal來做。
問題是怎麼用string variable來當做template literal的置換?
真的有神人po出解決方案。很久沒這麼開心了,這行程式碼,看了兩三遍才看懂。
心得:
趕快用es6吧,寫程式真的開心很多。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.231.146.94
※ 文章網址: https://www.ptt.cc/bbs/Soft_Job/M.1536044827.A.0B6.html
→ ddoll288: 直接看stackoverflow比較清楚 09/04 15:38
一定要看原來的stackoverflow。
→ fukinhot: 做得到 關鍵字:tagged template 09/04 18:35
tagged template很好用
→ dreamnook: 啊哈哈這招我有在我開發Game的時候用過xD 09/04 19:01
我覺得這東西還蠻神奇的。完全沒有從code generation的方向去想。
→ weiyucsie: 是不是要\`${templateString}\` ? 09/05 18:06
對對對,已修正。
→ justben: 為何不用i18n 很多套件啊 09/05 19:59
我不需要currency, decimal, date的轉換。目前自己寫的只需要4k(還沒zip).
※ 編輯: oopFoo (61.230.117.180), 09/06/2018 00:07:02