Always want to write a template engine used in their own code, because the previous use of an open source product, each time the need to adapt to meet some limitations, rather than write their own reality, want to change where to change, so today spent a little time to build a very small template engine, core functions already exist, The rest of the time until later to expand slowly.
The template engine, in a nutshell, is to find placeholders on the page, then replace them, and then insert them into the page, whether the functionality or the implementation method is extremely simple.
Placeholders can also be seen in two places:
- Text node
- Property value
By ChildNodes can find the text node, through the attributes can find all the existing attribute values under the element, so look at the code, the following code implements the function of looking up placeholders
functionEachnode (ele) {//See if a property needs to be converted to its own properties varAttrs =ele.attributes; varChildNodes =Ele.childnodes; //traverse the attribute node of the current element for(varA = 0,alen = attrs.length;a<alen;a++) { //determine if the value of the package {{}} is useful in Attrs[a].value if(/\{\{.*?\}\}/. Test (Attrs[a].value)) { //if not, you can also use this method //Attrs[a].value.indexof ("{{")! =-1 && attrs[a].value.indexof ("}}", Attrs[a].value.indexof ("{{")) //--------------------------------// //The evaluation expression is executed here } } //iterates over the child nodes of the current element for(varc = 0,clen = childnodes.length;a<clen;a++) { //If the current child node is a text node, and the content is wrapped by {{}} if(Childnodes[c].nodetype = = = 3 &&/\{\{.*?\}\}/. Test (Childnodes[c].data)) { //The evaluation expression is executed here}Else if(Childnodes[c].nodetype!== 8) { //Skipping comment nodesEachnode (Childnodes[c]) }}}
With this code, you can find all the data that needs to be transformed under an element, and if you need to find the entire HTML that needs to be transformed, just pass in the HTML node: eachnode ( Document.documentelement) ,
After finding the data that needs to be transformed in the two nodes that need to transform the data,
You need to convert them, you need a value that corresponds to one by one of them,
In general, there will be an object that assigns a placeholder to the node that needs to be converted, and one by one corresponds to the attribute in this object;
The following code allows you to replace the original placeholder, then a mini template engine is developed.
//In any way, there are some values that correspond to the placeholder one by one on the page,//The following is an object that holds these valuesvarobj ={test:1, Textnode:"Hello world!", class:"Body"}//by the result of the above traversal//It is generally possible to obtain such data//JavaScript {{Textnode}}//I need to convert textnode into Hello world.functionReplace (text) {//replace placeholders with the Replace methodText = Text.replace (/\{\{.*?\}\}/g,function(m) {//m = = = {{Textnode}} returnObj[m.replace (/\{\{|\}\}/g,function(m) {return""; })]; }) Console.log (text); //after printing, you will find that you have replaced the original placeholder with the value in the object .}//Try printing This text on the console//var text = "JavaScript {{Textnode}} + {{class}}} = = = {{test}}";//Replace (text)
Well, so far a simple mini-version of the template engine has been set up, the rest if not involved in the calculation, through this method can also be extrapolate to create wheels.
And all the regular expressions above can be simulated.
Replace placeholder (non-regular method, extrapolate by this method)
vararr = [];functionGetplace (text) {varStart = Text.indexof ("{"); varEnd = Text.indexof ("}}"); //If there are {{and}} inside the string if(Start! =-1 && End! =-1) { //intercept strings and save themArr.push (Text.substring (start,end+2)); //If after interception there is still {{ //Continuecallback again to save the following placeholder in arr if(Text.indexof ("{{", end+2)! =-1) {getplace (Text.substr (Text.indexof ("{", end+2))); }}}getplace ("The character {{}}} ' needs to be substituted for {{in}}");//Traverse Replacement String for(varI =0,ilen = arr.length;i<ilen;i++) {text= Text.replace (Arr[i],function(m) {return"Substituted character"; })}
At this point a mini-version of the template engine was developed. On GitHub you can see a little bit of a powerful template engine with the ability to compute, uttered estimates only 60 lines of code.
Transmission Door
Write a mini template engine