简单的js模板工具

  在写代码的过程中,经常会用到模板,于是自己也写个模板小工具。

  最简单的模板也就是字符替换,先用一个占位符${name},然后再用一个数据替换它,eg:${name}=>Dane

  在查找点位符时,要用到正则表达式(http://www.w3school.com.cn/js/js_obj_regexp.asp),查找${name}这样一个占位符可用下面正则表达式:

  

1 var patt = new RegExp('\\u0024\\u007B'+name+'\\u007D','g');
2 result = result.replace(patt,data[d]);

  其中\unnnn 意思是匹配4个16进制的Unicode。如果不用Unicode用转义,这个还没弄出来,我试过\$\{name\},但出错了,按在网上查的:“\”+实际字符 \ . * + ? | ( ) { }^ $ 例如:\\匹配字符“\”;貌似不起作用。

  把它写成一个js函数如下:

 1     function strict(types, args){
 2       if(types.length != args.length){
 3           throw 'Invalid number of arguments.'
 4        }
 5        for (var i = args.length - 1; i >= 0; i--) {
 6             if(args[i].constructor != types[i]){
 7                 throw 'Invalid argument type.';
 8             }
 9         };
10     }
11     function tplTool(tpl, data){
12         var result = tpl;
13         strict([String,Object],arguments);
14         for(var d in data){
15             var patt = new RegExp('\\u0024\\u007B'+d+'\\u007D','g');
16             result = result.replace(patt,data[d]);
17         }
18         return result;
19    }

  strict用来检查传入参数

      完整小例子:

 1 <!DOCTYPE HTML> 
 2 <html> 
 3     <head> 
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
 5     <title>tpl</title>
 6     <style type="text/css">
 7         body{text-align: center;}
 8         .imgContent{margin-left: auto;margin-right: auto;margin-top: 50px;border: 2px dotted #ccc;display: inline-block;border-radius: 8px;}
 9         .imgContent img{border-radius: 8px;width: 700px;height: 400px;display: block;}
10     </style>
11     <script type="text/javascript">
12         var imgTpl = [
13             '<div class="${contentClass}">',
14                 '<img src="${imgSrc}" />',
15             '</div>'
16         ];
17         var data = {
18             contentClass:'imgContent',
19             imgSrc:'dog.jpg'
20         }
21         function strict(types, args){
22             if(types.length != args.length){
23                 throw 'Invalid number of arguments.'
24             }
25             for (var i = args.length - 1; i >= 0; i--) {
26                 if(args[i].constructor != types[i]){
27                     throw 'Invalid argument type.';
28                 }
29             };
30         }
31         function tplTool(tpl, data){
32             var result = tpl;
33             strict([String,Object],arguments);
34             for(var d in data){
35                 var patt = new RegExp('\\u0024\\u007B'+d+'\\u007D','g');
36                 result = result.replace(patt,data[d]);
37             }
38             return result;
39         }
40         window.onload = function(){
41             document.body.innerHTML = tplTool(imgTpl.join(''),data);
42         }
43     </script>
44     </head> 
45     <body> 
46     </body> 
47 </html>  

 

posted @ 2013-04-25 16:10  jinphen  阅读(564)  评论(2编辑  收藏  举报