JS模板引擎jTemplates 使用笔记(一)
1 引擎简介
jTemplates是一个基于Jquery的js模板引擎插件。该引擎全部代码由JS实现,可以配合AJAX,JSON一起协同工作,模板内容可以用JS代码,实现了活动更新,可以自动从服务器更新模板生成的内容。
jTemplates能免费应用于商业和非商业。
2 下载引用
最新版本号:0.7.8
示例包:http://jtemplates.tpython.com/jTemplates.zip
压缩后:http://jtemplates.tpython.com/jTemplates/jquery-jtemplates.js
未压缩:http://jtemplates.tpython.com/jTemplates/jquery-jtemplates_uncompressed.js
3 简单示例
本Demo使用MVC框架搭建。
I:使用*.ASCX搭建模板内容
主要代码
{#template MAIN} <div id="header">{$T.Name}</div> <table> {#foreach $T.Peoples as record} {#include ROW root=$T.record} {#/for} </table> {#/template MAIN} {#template ROW} <tr bgcolor="{#cycle values=['#AAAAEE','#CCCCFF']}"> <td>{$T.FirstName.bold()}</td> <td>{$T.Age}</td> <td>{$T.Email.link('mailto:'+$T.Email)}</td> </tr> {#/template ROW}
II: 使用*.Aspx搭建展示页面
主要代码
<script src="<%=Url.Content("~/Scripts/jquery-jtemplates.js")%>" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $.ajax({ type:"POST", url: "<%= Url.Action("GetData") %>", data: "", contentType: "application/json; charset=utf-8", cache:false, dataType: "json", success: function(data){ if(data){ $("#jTemplateDemo").setTemplateURL("<%=Url.Action("GetTemplate")%>"); $("#jTemplateDemo").processTemplate(data); } } }); }); </script> <div id="jTemplateDemo"></div>
III:Action和Model
Action主要代码
public ActionResult Index(string id) { return View(); } /// <summary> /// Request for template content /// </summary> /// <returns>templates</returns> public ActionResult GetTemplate() { return PartialView("TableTemp"); } /// <summary> /// Request for temp data /// </summary> /// <returns>temp data</returns> [HttpPost] public ActionResult GetData() { var model = new TempModel{ Name = "New Employees", Peoples = new List{ new Person {ID = "1", FirstName = "Anne", Email = "anne@domain.com",Age=20}, new Person {ID = "2", FirstName = "Amelie", Email = "amelie@domain.com",Age=22}, new Person {ID = "3", FirstName = "Polly", Email = "polly@domain.com",Age=35}, new Person {ID = "4", FirstName = "Alice", Email = "alice@domain.com",Age=27}, new Person {ID = "5", FirstName = "Martha", Email = "martha@domain.com",Age=32} } }; return Json(model); }
Model主要代码
public class Person { public string ID { get; set; } public string FirstName { get; set; } public string Email { get; set; } public int Age { get; set; } } public class TempModel { public string Name { get; set; } public List<Person> Peoples { get; set; } }
3 运行效果图
■ 拿起勇气,探索你未知的世界。