有了 each 的经验后,要实现 if/else 这种指令就简单了-------在 case '}' 处对 varcode 进行指令的判断即可。
模板代码:
{if data.value==1}
<h3>11111111111</h3>
{else-if data.value==2}
<h3>22222222222</h3>
{else}
<h3>33333333333</h3>
{/if}
目标代码:
function func(data) {
var result = []; result.push(" ");
if (data.value == 1) {
result.push(" <h3>11111111111</h3> ");
} else if (data.value == 2) {
result.push(" <h3>22222222222</h3> ");
} else {
result.push(" <h3>33333333333</h3> ");
} result.push(" ");
return result.join("");
}
分析:
>这里我们直接对照代码来看, 对于 if 和 else-if ,花括号 {} 内的内容,除了作为 指令识别字符 的 if/else-if 空格分隔后的第二个都是按照原样当作 js 代码来处理的。而不管是 if还是 else if 我们会发现 我们写js代码时,一般都会用 {} 将方法体抱起来(单行一般不需要包也可以,但是这里统一使用 {} 来包住方法体),而 if () 之后接的 就是 { 。
>对于 else/else-if 指令,通过代码我们看到, else 即代表 前一个情况的处理结束了, 那就需要 } 包回来,同时 else 说明了 另一个情况的开始,所以后面需要 加上 { 开始新的方法体。
>/if 跟 /each 一样,这里的 /if 代表这一层的判断结束,遇到 /if 时只需要 将方法体包回来 ,所以 提供 } 即可。
实现代码:
function Template2code(template) {
var resultcode = [];
resultcode.push("function func(data) { var result=[];");
var tempcode = [];
var varcode = [];
var isvarcode = false;
var eachIndex = 0;
for (var key in template) {
var value = template[key];
//console.log(value);
switch (value) {
case "\n":
if (isvarcode) {
varcode.push(" ")
}
else {
tempcode.push(" ");
}
break;
case "\"":
if (isvarcode) {
varcode.push("\\\"")
}
else {
tempcode.push("\\\"");
}
break;
case "{":
isvarcode = true;
resultcode.push(" result.push(\"" + tempcode.join("") + "\") ;");
tempcode = [];
break;
case "}":
isvarcode = false;
var varvalue = varcode.join("");
if (varvalue.indexOf("each") == 0) {
// each index,value arr
var eachInfo = varvalue.split(' ');
if (eachInfo.length != 3) throw "each 参数无效:each index,value arr";
var itemInfo = eachInfo[1].split(',');
if (itemInfo.length != 2) throw "each 参数无效:each index,value arr";
resultcode.push("for (var " + itemInfo[0] + " in " + eachInfo[2] + ") {var " + itemInfo[1] + " = " + eachInfo[2] + "[" + itemInfo[0] + "];");
}
else if (varvalue === "/each") {
resultcode.push(" }");
}
else if (varvalue.indexOf("if") == 0) {
var ifInfo = varvalue.split(" ");
resultcode.push("if(" + ifInfo[1] + "){");
}
else if (varvalue.indexOf("else-if") == 0) {
var ifInfo = varvalue.split(" ");
resultcode.push(" } else if(" + ifInfo[1] + "){");
}
else if (varvalue.indexOf("else") == 0) {
var ifInfo = varvalue.split(" ");
resultcode.push(" } else {");
}
else if (varvalue.indexOf("/if") == 0) {
resultcode.push(" }");
}
else {
resultcode.push(" result.push(" + varvalue + ") ;");
}
varcode = [];
break;
default:
if (isvarcode) {
varcode.push(value)
}
else {
tempcode.push(value);
}
}
}
resultcode.push(" result.push(\"" + tempcode.join("") + "\") ;");
resultcode.push("return result.join(\"\");}")
return resultcode.join("");
}
传入数据:
var data = {
value: 3
}
渲染结果:
<h3>33333333333</h3>
在 each 的基础上 处理 if 是简单很多了,这里也一篇就处理完了。
下一篇 处理 需要输出的内容里包含 {或者 } 的情况
目录: