Javascript Template笔记

 1 (function(){
 2     var cache = {};
 3     
 4     this.tmpl = function tmpl(str, data){
 5         // Figure out if we're getting a template, or if we need to
 6         // load the template - and be sure to cache the result.
 7         var fn = !/\W/.test(str) ?
 8         cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) :
 9         // Generate a reusable function that will serve as a template
10         // generator (and which will be cached).
11     new Function("obj",
12     "var p=[],print=function(){p.push.apply(p,arguments);};" +
13     // Introduce the data as local variables using with(){}
14     "with(obj){p.push('" +
15     // Convert the template into pure JavaScript
16     str
17     .replace(/[\r\t\n]/g, " ")
18     .split("<%").join("\t")
19     .replace(/((^|%>)[^\t]*)'/g, "$1\r")
20     .replace(/\t=(.*?)%>/g, "',$1,'")
21     .split("\t").join("');")
22     .split("%>").join("p.push('")
23     .split("\r").join("\\'")
24     + "');}return p.join('');");
25     // Provide some basic currying to the user
26     return data ? fn( data ) : fn;
27     };
28     })();
29     
30     assert( tmpl("Hello, <%= name %>!", {name: "world"}) ==
31     "Hello, world!", "Do simple variable inclusion." );
32     var hello = tmpl("Hello, <%= name %>!");
33     assert( hello({name: "world"}) == "Hello, world!",
34     "Use a pre-compiled template." );    
35 }
36 /**动态生成的函数*/ 37 function(obj){ 38 var p=[],print=function(){p.push.apply(p,arguments);}; 39 with(obj){p.push(' 40 str 41 .replace(/[\r\t\n]/g, " ") 42 .split("<%").join("\t") 43 .replace(/((^|%>)[^\t]*)'/g, "$1\r") 44 .replace(/\t=(.*?)%>/g, "',$1,'") 45 .split("\t").join("');") 46 .split("%>").join("p.push('") 47 .split("\r").join("\\'") 48 '); 49 } 50 return p.join('');
<html>
    <head>
        <script type="text/tmpl" id="colors">
            <p>Here's a list of <%= items.length %> items:</p>
            <ul>
            <% for (var i=0; i < items.length; i++) { %>
            <li style='color:<%= colors[i % colors.length] %>'>
            <%= items[i] %></li>
            <% } %>
            </ul>
            and here's another...
        </script>
        <script type="text/tmpl" id="colors2">
            <p>Here's a list of <%= items.length %> items:</p>
            <ul>
            <% for (var i=0; i < items.length; i++) {
            print("<li style='color:", colors[i % colors.length], "'>",
            items[i], "</li>");
            } %>
            </ul>
        </script>
        <script src="tmpl.js"></script>
        <script>
            var colorsArray = ['red', 'green', 'blue', 'orange'];
            var items = [];
            for ( var i = 0; i < 10000; i++ )
            items.push( "test" );
            function replaceContent(name) {
            document.getElementById('content').innerHTML =
            tmpl(name, {colors: colorsArray, items: items});
            }
        </script>
    </head>
    <body>
        <input type="button" value="Run Colors"
            οnclick="replaceContent('colors')">
        <input type="button" value="Run Colors2"
            οnclick="replaceContent('colors2')">
        <p id="content">
            Replaced Content will go here
        </p>
    </body>
</html>
posted on 2012-08-23 11:34  坏小仔 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/you0630/archive/2012/08/23/2652157.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值