前一篇说了jsrender嵌套循环的使用,在SPA的应用中,广泛使用的一个点就是view模板,使用了SPA之后,每个业务页面不再是独立的html,仅仅是一个segment,所以通常这些segment会被独立的存储,而不是跟demo一样嵌在宿主页面中。因为jsrender的模板本质上就是一个string,所以一般三方库angularjs/backbone.js都提供了加载外部模板的机制。其实原理都一样,差不多都是通过ajax从远程加载,然后缓存在B/S端,在jsrender中,通过类似机制,也可以达到一样的目标。如下所示:
render_seg.html
{{for #data}} <h3>{{:name}}</h3> <ul> {{for language}} <li> {{:#parent.parent.data.name}} is learning {{:title}}<br/> {{for scores}} <a href="#">{{:score}}</a> {{/for}} </li> {{/for}} </ul> {{/for}}
主页面jsrender_nest_external.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script type="text/javascript" src="jquery-1.11.1.min.js"></script> <script type="text/javascript" src="jsrender.js"></script> <title>jsrender nest external demo</title> </head> <body> <div id="studentList"></div> <script type="text/javascript"> var temps = {}; var url = "studentTemp"; var students = [{name:"张三",language:[{title:"中",scores:[{score:12},{score:13},{score:14}]},{title:"英",scores:[{score:12},{score:13},{score:14}]},{title:"数",scores:[{score:12},{score:13},{score:14}]}]}, {name:"李四",language:[{title:"中",scores:[{score:12},{score:13},{score:14}]},{title:"中",scores:[{score:12},{score:13},{score:14}]},{title:"中",scores:[{score:12},{score:13},{score:14}]}]}, {name:"王五",language:[{title:"中",scores:[{score:12},{score:13},{score:14}]},{title:"中",scores:[{score:12},{score:13},{score:14}]},{title:"中",scores:[{score:12},{score:13},{score:14}]}]}]; if(temps[url]) { var tmpl = $.templates(temps[url]); $("#studentList").html(tmpl.render(students)); } else { $.ajax({ url: "render_seg.html", //这里是静态页的地址 type: "GET", //静态页用get方法,否则服务器会抛出405错误 success: function (data) { temps[url] = data; var tmpl = $.templates(temps[url]); $("#studentList").html(tmpl.render(students)); } }); } </script> </body> </html>
其效果和内嵌模板完全相同,不过更加的干净。