作者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://webptt.com/cn.aspx?n=bbs/Soft_Job/M.1536044827.A.0B6.html
1F:→ ddoll288: 直接看stackoverflow比较清楚 09/04 15:38
一定要看原来的stackoverflow。
2F:→ fukinhot: 做得到 关键字:tagged template 09/04 18:35
tagged template很好用
3F:→ dreamnook: 啊哈哈这招我有在我开发Game的时候用过xD 09/04 19:01
我觉得这东西还蛮神奇的。完全没有从code generation的方向去想。
4F:→ weiyucsie: 是不是要\`${templateString}\` ? 09/05 18:06
对对对,已修正。
5F:→ justben: 为何不用i18n 很多套件啊 09/05 19:59
我不需要currency, decimal, date的转换。目前自己写的只需要4k(还没zip).
※ 编辑: oopFoo (61.230.117.180), 09/06/2018 00:07:02