JavaScript微模板substitute.js(参考dojo/string)
Email:longsu2010 at yeah dot net
之前写了关于dojo/string模块的文章如下:
dojo微模板dojo/string模块dojo模板字符串最佳实践
后来一时兴起把dojo/string模块中的substitute方法切出来作为一个独立的微模板使用。
已经提交到了github上,地址为https://github.com/notejs/substitute,使用方法可以参考test.html。
需要说明的是substitute.js与dojo/string模块的substitute方法的行为略有不同。
举例如下:
var template = "name is: ${name}, age is: ${age}"; var map = { name : "youjiang wang" };可以看出模板中出现两个模板标签,map中只给定一个属性,dojo/string模块的substitute会报错,substitute.js会将没匹配的模板标签原样输出。
可以读一下源码,代码量非常少,截图如下。
如果看不懂js字符串的replace方法可以参考JavaScript String.replace函数参数说明