Trimpath JavaScript 是个轻量级的,基于JavaScript的,跨浏览器,采用APL/GPL开放源代码协议的,可以让你轻松进行基于模板编程方式的纯JS引擎。新浪的评论系统使用的就是此模板。
它有如下的特点:
1、采用标准的JavaScript编写,支持跨浏览器
2、模板语法类似于:FreeMarker,Velocity,Smarty
3、采用简易的语言来描述大段的字串以及Dom/DHTML操作
4、可以很方便的解析XML文件格式的数据到指定模板。
采 用该引擎,可以让它来完全处理View方面的事情,服务端Module直接输出Data就可以。让你的MVC模式连成一体,而且由于View由浏览器来处 理,大大减少了服务器的负担,用来构建Ajax技术的网络信息系统应用是一个非常好的选择。下面将通过翻译该站的文章来给大家介绍这个JST引擎的使用。
CODE:
- <html>
- <head>
- <script language="javascript" src="trimpath/template.js"></script>
- </head>
- <body>
- <div id="outputDiv">
- </div>
- <script language="javascript">
- var data = {
- products : [ { name: "mac", desc: "computer",
- price: 1000, quantity: 100, alert:null },
- { name: "ipod", desc: "music player",
- price: 200, quantity: 200, alert:"on sale now!" },
- { name: "cinema display", desc: "screen",
- price: 800, quantity: 300, alert:"best deal!" } ],
- customer : { first: "John", last: "Public", level: "gold" }
- };
- </script>
- <textarea id="cart_jst" style="display:none;">
- Hello ${customer.first} ${customer.last}.<br/>
- Your shopping cart has ${products.length} item(s):
- <table>
- <tr><td>Name</td><td>Description</td>
- <td>Price</td><td>Quantity & Alert</td></tr>
- {for p in products}
- <tr><td>${p.name|capitalize}</td><td>${p.desc}</td>
- <td>$${p.price}</td><td>${p.quantity} : ${p.alert|default:""|capitalize}</td>
- </tr>
- {forelse}
- <tr><td colspan="4">No products in your cart.</tr>
- {/for}
- </table>
- {if customer.level == "gold"}
- We love you! Please check out our Gold Customer specials!
- {else}
- Become a Gold Customer by buying more stuff here.
- {/if}
- </textarea>
- <script language="javascript">
- // The one line processing call...
- var result = TrimPath.processDOMTemplate("cart_jst", data);
- // Voila! That's it -- the result variable now holds
- // the output of our first rendered JST.
- // Alternatively, you may also explicitly parse the template...
- var myTemplateObj = TrimPath.parseDOMTemplate("cart_jst");
- // Now, calls to myTemplateObj.process() won't have parsing costs...
- var result = myTemplateObj.process(data);
- // Setting an innerHTML with the result is a common last step...
- document.getElementById("outputDiv").innerHTML = result;
- // You might also do a document.write() or something similar...
- </script>
- </body>
- </html>