Trimpath JavaScript 是个轻量级的,基于JavaScript的,跨浏览器,采用APL/GPL开放源代码协议的,可以让你轻松进行基于模板编程方式的纯JS引擎。
它有如下的特点:
1、采用标准的JavaScript编写,支持跨浏览器
2、模板语法类似于:FreeMarker,Velocity,Smarty
3、采用简易的语言来描述大段的字串以及Dom/DHTML操作
采用该引擎,可以让它来完全处理View方面的事情,服务端Module直接输出Data就可以。让你的MVC模式连成一体,而且由于View由浏览器来处 理,大大减少了服务器的负担,用来构建Ajax技术的网络信息系统应用是一个非常好的选择。下面将通过翻译该站的文章来给大家介绍这个JST引擎的使用。
官方网站:
http://code.google.com/p/trimpath/wiki/JavaScriptTemplates
首先,在html页面上加载trimpath的js文件
<html> <head> <script language="javascript" src="trimpath-template-1.0.38.js"></script> </head> </html>
接下来,创建一个标准的javascript数据,比如是数组或者是objects
<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>
然后,我们创建一个JST模板来读取上面的数据,同时把模板的样式设置为不可见
<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.</td> </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>
以下的代码展示怎样使用JST来处理模板
<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); //var result2 = myTemplateObj.process(differentData); // Setting an innerHTML with the result is a common last step... document.getElementById('test').innerHTML = result; // You might also do a document.write() or something similar... </script>
页面展示的结果为:
Hello John Public. Your shopping cart has 3 item(s): Name Description Price Quantity & Alert MAC computer $1000 100 : IPOD music player $200 200 : ON SALE NOW! CINEMA DISPLAY screen $800 300 : BEST DEAL! We love you! Please check out our Gold Customer specials!
附件是以上描述的例子,供有兴趣的童鞋下载~~~