search
HomeWeb Front-endJS TutorialJavaScript template engine-tmpl bug repair and performance optimization analysis_javascript skills

There are many exquisite tmpl
front-end templates available in open source, but the “javascript micro templating” developed by jQuery author John Resig is the most exquisite. It realizes the core functions of the template engine in just a few strokes.
For its introduction and usage, please see the author's blog: http://ejohn.org/blog/javascript-micro-templating/
Let us take a look at his source code first:

Copy code The code is as follows:

(function(){
var cache = {};
this.tmpl = function (str, data){
var fn = !/W/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str). innerHTML):
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};"
"with(obj ){p.push('"
str
.replace(/[rtn]/g, " ")
.split(" .replace(/((^|%>)[^t]*)'/g, "$1r")
.replace(/t=(.*?)%>/g, "', $1,'")
.split("t").join("');")
.split("%>").join("p.push('")
.split("r").join("\'")
"');}return p.join('');");
return data ? fn( data ) : fn;
};
})();

Although the sparrow is small, it has all the internal organs. In addition to basic data attachment, it also has a caching mechanism and logic support. Now, if I were to rank the most energy-saving custom functions in JavaScript, the first place would be the $ function (document.getElementById short version), and the second place would be tmpl.
Of course, it is not perfect. I found some problems during use:
tmpl has a fly in the ointment
1. It cannot handle escape characters correctly, such as:
Copy code The code is as follows:
tmpl('// ', {name:'sugar Pie', id: '1987'});

It will report an error. If working properly, it should output: Sugar Cookie/1987
In fact, the solution is very simple, add a line of regex to escape the escape character:
Copy code The code is as follows:
str.replace(/\/g, "\\")

2. It sometimes cannot correctly distinguish the first parameter Is it an ID or a template.
If the page template ID is underlined, such as tmpl-photo-thumb, it will not look for the template with this name, and will think that the original template passed in is directly compiled and output.
The most intuitive difference between the original template and the element ID is whether it contains spaces, so just change the regular expression:
view sourceprint?1 !/s/.test(str)
3. It also has internal There is a code left for testing and can be deleted.
Copy code The code is as follows:
print=function(){p.push.apply(p,arguments );}

Doubts about tmpl efficiency
Until I read a soft article by Baidu mux introducing YayaTemplate some time ago, the author of the original article conducted efficiency tests on the major popular template engines, and finally concluded that YayaTemplate is the most popular template engine. A quick one. Although the test result of tmpl is not as good as YayaTemplate, it also allows me to dispel my concerns about performance. In actual application, it is almost the same as traditional string concatenation. There will be a large performance gap between them only when performing very large-scale analysis. (Super large-scale? JavaScript itself is not suitable for this. If one day a programmer inserts thousands of list data into the browser at one time and it is extremely slow, there is no doubt: the problem lies with this programmer, he is not Will cherish the user's browser. )
When it comes to engine efficiency rankings, I don't think this is the primary criterion for measuring template engines. Template syntax is also an important part. At this time, YayaTemplate's template syntax becomes obvious. Much more obscure, it uses a clever twist on template syntax to save a few regular expressions.
First show the source code of YayaTemplate:
Copy the code The code is as follows:

//author:yaya,jihu
//uloveit.com.cn/template
//how to use? YayaTemplate("xxx").render({});
var YayaTemplate = YayaTemplate || function(str){
//Core analysis method
var _analyze=function(text){
return text.replace(/{$(s|S)*?$} /g,function(s){
return s.replace(/("|\)/g,"\$1")
.replace("{$",'_s.push("')
.replace("$}",'");')
.replace(/{%([sS]*?)%}/g, '",$1,"')
}) .replace(/r|n/g,"");
};
//Intermediate code
var _temp = _analyze(document.getElementById(str)?document.getElementById(str).innerHTML: str);
//Return generator render method
return {
render : function(mapping){
var _a = [],_v = [],i;
for (i in mapping){
_a.push(i);
_v.push(mapping[i]);
}
return (new Function(_a,"var _s=[];" _temp " return _s;")).apply(null,_v).join("");
}
}
};

If the performance problem is raised to one A high-level attempt to solve the "academic problem", why is tmpl slower than YayaTemplate?
Grammar parsing? Although YayaTemplate uses a novel way of wrapping html with javascript, it ultimately needs to be parsed into a standard using regular expressions. JavaScript syntax, there will not be much difference in the efficiency of regularization, and both parties use a caching mechanism to ensure that the original template is only parsed once? The template engine will eventually save the data in the form of variables. In the closure so that the template can get it. Let’s first compare the variable declaration mechanisms of both parties:
YayaTemplate is implemented using the traditional method of passing parameters. It separates the name and value of the object by traversing the data object, and then uses the object member name as the parameter name of the new Function (that is, the variable name), and then uses the appley calling method of the function to pass those parameters.
tmpl is implemented using the with statement that is not commonly used in JavaScript. The implementation is very simple, omitting the var keyword.
The performance problem of tmpl lies in with. The with statement provided by javascript is intended to be used to access the properties of an object more quickly. Unfortunately, the presence of the with statement in the language severely slows down the JavaScript engine because it prevents lexical scoping of variable names.
Optimize tmpl
If tmpl removes the with statement and uses traditional parameter passing, the performance will be greatly improved immediately. After actual testing, under 240,000 pieces of data, Firefox can improve 5 times, Chrome 2.4 times, Opera 1.84 times, and Safari 2.1 times, IE6 1.1 times, IE9 1.35 times, and finally tied with YayaTemplate.
Test address: http://www.planeart.cn/demo/tmpl/tmpl.html
Tmpl optimized version final code:

Copy code The code is as follows:

/**
* Micro template engine tmpl 0.2
*
* 0.2 Update:
* 1. Fix the bug in escape character and id judgment
* 2. Abandon the inefficient with statement to achieve the highest improvement 3.5 times execution efficiency
* 3. Use random internal variables to prevent conflicts with template variables
*
* @author John Resig, Tang Bin
* @see http://ejohn.org/ blog/javascript-micro-templating/
* @name tmpl
* @param {String} Template content or element ID containing template content
* @param {Object} Additional data
* @return {String} Parsed template
*
* @example
* Method 1: Embed template in the page
*
* tmpl('tmpl-demo', {name: 'demo data', list: [202, 96, 133, 134]})
*
* method Two: Directly pass in the template:
* var demoTmpl =
* '
    '
    * ''
    * '
  1. '
    * ''
    * '
';
* var render = tmpl(demoTmpl);
* render({name: 'demo data', list: [ 202, 96, 133, 134]});
*
* The difference between these two methods is that the first one will automatically cache the compiled template,
* while the second cache is controlled by external objects , such as the render variable in Example 2.
*/
var tmpl = (function (cache, $) {
return function (str, data) {
var fn = !/s/. test(str)
? cache[str] = cache[str]
|| tmpl(document.getElementById(str).innerHTML)
: function (data) {
var i, variable = [$], value = [[]];
for (i in data) {
variable.push(i);
value.push(data[i]);
};
return (new Function(variable, fn.$))
.apply(data, value).join("");
};
fn.$ = fn.$ || $ " .push('"
str.replace(/\/g, "\\")
.replace(/[rtn]/g, " ")
.split(".replace(/((^|%>)[^t]*)'/g, "$1r")
.replace(/t=(.*? )%>/g, "',$1,'")
.split("t").join("');")
.split("%>").join($ ".push('")
.split("r").join("\'")
"');return " $;
return data ? fn(data) : fn;
}})({}, '$' ( new Date));

The template engine relies on the Function constructor, which like eval provides a method to access the javascript parsing engine using text. This will also significantly reduce performance, but at this point there is no other way in JavaScript.
Using the Function constructor also imposes restrictions on parameter names, so the naming of data members must be consistent with the JavaScript variable name specifications, otherwise an error will be reported. Fortunately, this error can be discovered immediately during operation and will not become a landmine.
Tips for using tmpl
1. Cache optimization.
tmpl performs caching optimization on templates embedded in the page by default (that is, when the first parameter is an ID), it will only analyze the template once. If the original template is passed directly into the first parameter of tmpl and needs to be used multiple times, it is recommended to cache it with a public variable and use it again when the data needs to be parsed to obtain the same optimization effect. For example:
Copy code The code is as follows:

// Generate template cache
var render = tmpl(listTmpl);
//The template can be called multiple times
elem.innerHTML = render(data1);
elem.innerHTML = render(data2);
...

2. Avoid undefined variables causing system crash.
If a variable output is defined in the template, and the incoming data is missing this item, an undefined variable error will occur, causing the entire program to crash. If data integrity cannot be ensured, there are still ways to probe its members. In the original version, the implicit variable saves the original incoming data, that is, obj; in my upgraded version, it is the keyword this, such as:
Copy code The code is as follows:



< ;% } %>

3. 디버깅 템플릿.
템플릿 엔진은 텍스트를 사용하여 자바스크립트 엔진을 호출하기 때문에 디버깅 도구는 오류 줄을 찾을 수 없습니다. 업그레이드된 버전에서는 디버깅 도구를 사용하여 컴파일된 템플릿 캐시를 출력할 수 있습니다. 예를 들어 다음 템플릿을 디버그합니다.
코드 복사 코드는 다음과 같습니다.

< ;script id="tmpl " type="text/tmpl">


  • . 사용자: ; .site%>< ;/li>



출력 캐시:
🎜>코드 복사 코드는 다음과 같습니다.
window.console(tmpl('tmpl').$)

로그 결과:

코드 복사 코드는 다음과 같습니다.
"$1318348744541 .push('
    ' ); for (var i = 0, l = list.length; i
  • ',list [i].index,'.사용자: ', list[i].user,'; 웹사이트:',list[i].site,'

  • ');

'); return $1318348744541"

이제 템플릿 엔진으로 컴파일된 javascript 문을 볼 수 있으며, 이에 대해 템플릿에 오류가 있는지 확인할 수 있습니다. ($1318348744541은 임의의 이름을 가진 임시 배열이므로 무시할 수 있습니다.)
마지막으로 tmpl의 원저자와 YayaTemplate의 저자의 노고에 깊은 감사를 드립니다. 구현 메커니즘을 분석하고 문제를 해결하며 그로부터 이익을 얻습니다. 혼자서 행복하는 것은 다른 사람과 함께하는 행복만큼 좋지 않습니다. 공유하십시오.
탕빈 – 2011.10.09 – 후난-창사
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),