Before the holiday prepared to chew chart.js source (good difficult to chew%>_<%), just learn the use of canvas. Gnawing at gnawing out a template source code.
This JS template comes from the blog of jqueryJohn resig. The code adds a comment to 35 lines, but fully implements the function of the template function.
Usage is similar to other templates (baidutemplate.js,underscore.js with templates), here is an example:
First, the script tag contains the template:
<Scripttype= "text/html"ID= "User_tmpl"> <% for ( varI= 0; I<users.length; I++ ) { %> <Li><a href="<%=users[i].url%>"><%=Users[i].name%></a></Li> <% } %> </Script>
JS Code:
var result = document.getElementById (' result '); var users = [{ ' aaaa ', ' http://baidu.com ' },{ ' bbbb ', ' http://baidu.com ' },{ ' CCCC ', ' http://baidu.com ' } ]; var data = { users:users } = Tmpl (' User_tmpl ', data);
This is a common usage, and in addition, there is another way to use it.
Get the template function by ID and then execute the function later to get the result. Like what:
var show_user = Tmpl (' User_tmpl '), = '; for (var i = 0; i < users.length; i++) { console.log (Show_user (Users[i]) }
Note: The array used for this loop must be the users, as in script, or there will be an error.
The source code is posted here and later resolved:
//Simple JavaScript Templating//John resig-http://ejohn.org/-MIT Licensed(function(){ varCache = {}; This. Tmpl =functionTmpl (str, data) {//Figure out if we ' re getting a template, or if we need to //load the Template-and is sure to cache the result. varfn =!/\w/.test (str)?Cache[str]= Cache[str] | |Tmpl (document.getElementById (str). InnerHTML)://Generate A reusable function that would serve as a template //generator (and which'll be cached). NewFunction ("obj", "Var p=[],print=function () {p.push.apply (p,arguments);};" +//introduce the data as local variables using with () {}"With (obj) {P.push ('" +//Convert the template into pure JavaScriptstr. replace (/[\r\t\n]/g, ""). Split ("<%"). Join ("\ T"). Replace (/((^|%>) [^\t]*] '/g, ' $1\r '). Replace (/\t= (. *?) %>/g, "', $, '"). Split ("\ T"). Join ("');"). Split ("%>"). Join ("P.push ('"). Split ("\ r"). Join ("\ \")) + "');} Return P.join (");); //provide some basic currying to the user returnData?fn (data): FN; };}) ();
JavaScript dapper templates (top)