What do you do to convert a set of records from a database into an HTML output to an interface?
In the WebForm era we often used the DataGrid, Repeater, and when MVC came out we started writing C # looping statements directly on the view, and now I prefer to use the JavaScript template engine to generate HTML. Because the biggest benefit of this approach is the decoupling of the front-end code, the front-end developers do not need to know too much C # knowledge.
Usage and examples:
The first step is to introduce the JavaScript template engine to the page:
function template (str, data) {varStrfunc ="var p=[],print=function () {p.push.apply (p,arguments);};"+"With (obj) {p.push ('"+Str.replace (/[\r\t\n]/g," "). Replace (/'(?=[^#]*#>)/g, "\ t"). Split ("'"). Join ("\ \ '"). Split ("\ t"). Join ("'"). Replace (/<#= (. +?) #>/g,"', $, '"). Split ("<#"). Join ("');"). Split ("#>"). Join ("P.push ('") +"');} Return P.join (");"; Func=NewFunction ("obj", Strfunc); returnfunc (data);}
The second step is to prepare the HTML template:
<script type="text/html" id="temp_class"> for (var i=0; i<datalist.length;i++) {#> class="Panle ">
Course Name: <#= Datalist[i]. ClassName #> </div> <#} #></script>
The third step is to prepare the data with the output HTML:
function LoadPage () {varClasslist =[{ClassName:"Data Structure", ClassId:"1001", Createon:"2015-05-01 08:20:36", CreatedBy:"Administrator"}, {ClassName:"linear algebra", ClassId:"1003", Createon:"2015-05-03 19:21:25", CreatedBy:"Administrator"}, {ClassName:"Advanced Mathematics", ClassId:"1004", Createon:"2015-05-03 19:20:39", CreatedBy:"Administrator"} ]; varstrtemphtml = document.getElementById ("Temp_class"). InnerHTML; document.getElementById ("class_list"). InnerHTML =Template (strtemphtml, {datalist:classlist});}
Note: Classlist objects are output by back-end developers, and in MVC we can use the ViewBag object to output back-end variables to JavaScript code directly.
Effect preview:
Other template engine Description: Underscore.js
Summary of Advantages:
1, front-end personnel can be more free to change the HTML structure, no longer rely on background development.
2, template syntax support if and other JavaScript syntax, simple usage, reduce the complexity of code.
3, the HTML code structure is clear, can read strong.
This demo:
JavaScript template engine Learn to share