dojo微模板dojo/string模块

Email:longsu2010 at yeah dot net
知道John Resig的JavaScript Micro-Templating的人都知道其简洁性以及实现代码量及少。
dojo在dojo/string模块中提供了一个非常简洁的模板替换函数substitute。

先来个例子

require(["dojo/string"], function(string){
	var html = "File '${name}' is not found in directory '${info.dir}'.";
	var s = string.substitute(html, { name: "foo.html", info: { dir: "/temp" } });
	console.log(s);
});

输出结果为:
File 'foo.html' is not found in directory '/temp'.
可以看出substitute的第一参数是模板字符串,第二参数是替换的数据。

用法二:
var html = "File '${0}' is not found in directory '${1}'."
console.log(string.substitute(html , ["foo.html","/temp"] ));
输出结果为:
File 'foo.html' is not found in directory '/temp'.
可以看出第二参数可以是一个数组,模板中必须用下标的形式来表示。

substitute的方法签名为:substitute(/*String*/ template, /*Object|Array*/map, /*Function?*/ transform, /*Object?*/ thisObject)

用法三:

require(["dojo/string"], function(string){
	var fmts = {
		fmt : function(value){
			console.log("fmt : ", value);
			return "-" + value + "-";
		},
		transform : function(value, key){
			console.log("transform : ", value, key);
			return key + " : " + value;
		}
	}
	var html = "File '${name:fmt}' is not found in directory '${info.dir}'.";
	var s = string.substitute(html, { name: "foo.html", info: { dir: "/temp" } }, fmts.transform, fmts);
	console.log(s);
});

输出结果为:

fmt :  foo.html
transform :  -foo.html- 
transform :  /temp info.dir 
File 'name : -foo.html-' is not found in directory 'info.dir : /temp'. 

说明:
1、如上${name:fmt}为name这个属性要使用fmt函数来格式化。
2、substitute的第三参数为一个转换函数(可选),每替换一个模板变量的时候就会调用该函数(参数为模板变量值及模板变量名字),如果没有该参数则使用第四参数中的transform函数,如果第四参数中无transform则不执行此操作。
3、substitute的第四参数为一个对象(可选,默认为全局对象)。当模板引擎遇到${name:fmt}模板变量时会到该对象中查找fmt函数。如果没有提供第三参数,并且该对象中包含一个名为transform的函数,则用使用该transform作为第三参数。


dojo/string模块除了提供substitute函数外还提供了如下函数:
reg(/*String*/str, /*Integer*/num):将第一参数的字符串复制第二参数次。
pad(/*String*/text, /*Integer*/size, /*String?*/ch, /*Boolean?*/end):将text用ch填充到长度为size,end为true则在text后面填充,否则在前面填充。
trim:trim就是String原型中的trim,若String原型中没有trim(js引擎不支持)则dojo实现功能相同trim。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值