Through the last piece has been able to replace the placeholder with the value of the corresponding variable, the implementation of a simple mini template engine, template engine a good function is to be able to calculate some simple expression, the core of the computation expression is actually the execution string, the method of executing the string is various eval,function, SetTimeout and so on, can be executed, as to which method, the benevolent see of the beholder.
Here's a look at the expressions you'll encounter in the template engine:
{A + B} //normal evaluation expression falsefalse! A}//non-op ...
Common expressions, non-operations, comparison
These three kinds of expressions, is simply to replace the variables, and then determine whether it is a number, the last time to execute the string will be able to parse the expression directly, so the following resolves these operators.
//replace an operator within an expressionvarm = "1 + 2 + 3-1 + Test";varobj ={test:1}
The value of the processing operator
This simply handles the plus and minus operation M= M.replace (/[^\+-\s]*/g,function(varmatch) {//if It's not a number //and in the corresponding object has this attribute if(Number (varmatch)! = number (Varmatch) &&Obj[varmatch]) { if(typeofObj[varmatch] = = = "Number") { returnObj[varmatch]; }Else{ return"'" + Obj[varmatch] + "'"; } }Else{ returnVarmatch; }}); Console.log (m);
Regardless of the method, the parsing expression must execute a string expression, so the method is tens of thousands of ways, the purpose is only one, the following is an example of a complete executable parse expression.
varOriginaldata ={jquery:"Hello jquery", angular:"Two-way data binding", react:"The Fast and the Furious"}varText = "I like {{jquery + angular}}, but in recent years {{angular = = angular}} seems to be a direction, but with {{react = = false}}, let me hesitate whether I should apply for Lanxiang study {{}}}"activeexpresstion (text,originaldata);functionactiveexpresstion (text,obj) {varOperatorreg =/[\+-\/\*\=\!] */G; varVariablereg =/[^\+-\/\*=\!\s]+/G; varPlacereg =/\{\{.*?\}\}/G; varExpressvalue;
Remove each set of {{}} placeholders that contain the text= Text.replace (Placereg,function(m) {m= M.substring (2,m.length-2); //determine if there are operators if(Operatorreg.test (m)) {m= M.replace (Variablereg,function(varmatch) {//if It's not a number //and in the corresponding object has this attribute if(Number (varmatch)! = number (Varmatch) &&Obj[varmatch]) { if(typeofObj[varmatch] = = = "Number") { returnObj[varmatch]; }Else{ return"'" + Obj[varmatch] + "'"; } }Else{ returnVarmatch; }}) eval ("Expressvalue =" +m); returnExpressvalue; }Else { if(Obj[m]) {returnObj[m]}Else{ returnm; } } }); returntext;}
[self-made template engine] adds analytic expression functionality to the template engine