A previous article briefly introduced the JavaScript Template (hereinafter referred to as Tmpl). It acts as a front-end template, powerful and code-refining. The source is not long, it is not difficult to read, but the idea is really sharp. This is the GitHub address. The following first put out all the source code, and then step-by-step analysis.
1 /*2 * JavaScript Templates 2.4.13 * Https://github.com/blueimp/JavaScript-Templates4 *5 * Copyright, Sebastian Tschan6 * Https://blueimp.net7 *8 * Licensed under the MIT license:9 * Http://www.opensource.org/licenses/MITTen * One * Inspired by John Resig ' s JavaScript micro-templating: A * http://ejohn.org/blog/javascript-micro-templating/ - */ - the /*jslint evil:true, regexp:true, Unparam:true*/ - /*Global document, define*/ - -(function ($) { +"Use Strict"; - varTmpl =function(str, data) { + varf =!/[^\w\-\.:]/.test (str)? TMPL.CACHE[STR] = Tmpl.cache[str] | | A Tmpl (Tmpl.load (str)): at NewFunction ( -Tmpl.arg + ', Tmpl ', -"var _e=tmpl.encode" + Tmpl.helper + ", _s= '" + -Str.replace (Tmpl.regexp, Tmpl.func) + -"'; return _s;" - ); in returnData? F (data, Tmpl):function(data) { - returnf (data, tmpl); to }; + }; -Tmpl.cache = {}; theTmpl.load =function(ID) { * returndocument.getElementById (ID). InnerHTML; $ };Panax NotoginsengTmpl.regexp =/([\s ' \ \ \]) (?! (?:[^{]|\{(?!%)) *%\})| (?:\ {%(=|#) ([\s\s]+?)%\}) | (\{%)| (%\}) /G; -Tmpl.func =function(S, p1, p2, p3, P4, p5) { the if(p1) {//whitespace, quote and backspace in HTML context + return { A"\ n": "\\n", the"\ r": "\\r", +"\ T": "\\t", -" " : " " $}[P1] | | "\\" +P1; $ } - if(p2) {//interpolation: {%=prop%}, or unescaped: {% #prop%} - if(P2 = = "=") { the return"' +_e (" + p3 + ") + '"; - }Wuyi return"' + (" + p3 + "==null": "+ P3 +") + ' "; the } - if(p4) {//Evaluation start tag: {% Wu return"‘;"; - } About if(p5) {//Evaluation end tag:%} $ return"_s+= '"; - } - }; -Tmpl.encreg =/[<>& "' \x00]/G; ATmpl.encmap = { +"<": "<", the">": ">", -"&": "&", $"\" ":" " ", the"'": "& #39;" the }; theTmpl.encode =function(s) { the /*Jshint eqnull:true*/ - return(s = =NULL? "" : "" +s). Replace ( in Tmpl.encreg, the function(c) { the returnTmpl.encmap[c] | | ""; About } the ); the }; theTmpl.arg = "O"; +Tmpl.helper = ", Print=function (s,e) {_s+=e? ( S==null? ': s): _e (s);} " + -", Include=function (s,d) {_s+=tmpl (s,d);}"; the if(typeofdefine = = = "function" &&define.amd) {BayiDefinefunction () { the returnTmpl; the }); -}Else { -$.tmpl =Tmpl; the } the}( This));
The purpose of this tool is to convert the template statements into JS statements, execute them, and then output them.
Look at lines 80 through 86 first, if it is based on Requirejs or Seajs,tmpl object is returned by define. If not, put it in the Tmpl object of the current environment (in the case of a browser environment, the current environment is window). This technique for compatibility with different reference methods is also useful when writing some of your own external common methods.
Next, we start from the beginning. In the beginning, a lot of comments, library names, license, JavaScript micro-templating inspired, described the content. Starting from line 18th, it is the entrance to the library. Line 20 begins to define the Tmpl function object, which is the str,data of the function. STR can be either a template or an ID for a template element. Data is a JSON object that needs to be replaced. Data can not be passed, and Tmpl returns a tool function that transforms the JSON object.
Line 21st defines the F function, and the F function is the core of the entire tool. Here, first check if STR is ID (str) (It is not clear how the ID will have:), if not, it means that Str is a template, it returns the new Function () {} (see line 23) through this template. If it is an ID, first check whether there is a corresponding function in the cache (the function in the cache is to be set beforehand, see the tool's documentation), if not, call itself, pass in the template element in the innerHTML (see 34 line Tmpl.load function), return the parameter data function. As you can see, the F function is finally a function that will manipulate the data and Tmpl objects and return the result of the entire Tmpl function. The procedure for this operation is within a function that is generated in 23 rows.
Let's take a look at what the 23-line generated function does. A formal parameter of this function is ' o ' (see Line 77), which can be modified by setting Tmpl.arg. There is also a formal parameter of ' Tmpl ', which is the Tmpl object itself. In the body part of the function, the _E function is defined, which is the tool function for escaping (see Line 68). Also defines _s, which is the last string to output. Also defines some auxiliary functions (see 78 rows), the default auxiliary function has two, the print function is used to add a string to the _s, you can set whether the string is escaped. The Include function can convert other templates and data into strings to _s. You can write some custom functions by rewriting Tmpl.helper, for example: tmpl.helper+= ", Alert=function (str) {window.alert (str);}"; This allows the alert function to be called in the template statement.
Then look at line 26th, by str.replace the Str into a valid sentence in JS. First look at the regular part (37 rows) and the corresponding function (38 rows), the replacement function P1 matches some whitespace characters, single quotes and slashes, and these characters are not within {% and%} (see ' (?! (?:[^{]|\{(?!%)) *%\}), the matching function will put these characters in front of the backslash to achieve escape. P2 matches the ' = ' in ' {%= ' or ' # ' in ' {% # ', and if the match is ' = ', the _e function is used to escape the variable within the P3 (a variable after the function body is transformed). P4 matches ' {% ', replaced by '; '. P5 matches '%} ', replaced by ' _s+= ';
After these matches and substitutions, the function body is pieced together. 29 line is to determine if there is a data parameter, if any, then convert. If not, a converted tool function is returned.
Attached: To here, also is barely say finish. A lot of details are omitted, even if you want to be clear and difficult to organize. After all, the standard is not good, slowly practice it ....
Javascript Template Source Parsing