网站模板套用教程 js网站模板素材( 三 )


var section;
var currentCondition;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
var value = https://www.520longzhigu.com/diannao/token.value;
var symbol = token.type;
switch (symbol) {
case ‘#’: {
collector.push(token);
sections.push(token);
if(token.action === ‘each’){
collector = token.children = [];
} else if (token.action === ‘if’) {
currentCondition = value;
var conditionArray;
collector = conditionArray = [];
token.conditions = token.conditions || conditionsArray;
conditionsArray.push({
condition: currentCondition,
collector: collector
});
}
break;
}
case ‘else’: {
if(sections.length === 0 || sections[sections.length – 1].action !== ‘if’) {
throw new Error(‘else 使用错误’);
}
currentCondition = value;
collector = [];
conditionsArray.push({
condition: currentCondition,
collector: collector
});
break;
}
case ‘/’: {
section = sections.pop();
if (section && section.action !== token.value) {
throw new Error(‘指令标签未闭合’);
}
if(sections.length > 0){
var lastSection = sections[sections.length – 1];
if(lastSection.action === ‘each’){
collector = lastSection.chidlren;
} else if (lastSection.action = ‘if’) {
conditionsArray = [];
collector = nestedTokens;
}
} else {
collector = nestedTokens;
}
break;
}
default: {
collector.push(token);
break;
}
}
}
return nestedTokens;
}
上一步我们生成了AST,这个AST在这里就是一个分词token数组:
[
Token {},
Token {},
Token {},
]
这个token就是每一段字符串,分别记录了token的类型,动作,子token,条件token等信息 。
/**
* token类表示每个分词的标准数据结构
*/
function Token (type, value, action, children, conditions) {
this.type = type;
this.value = https://www.520longzhigu.com/diannao/value;
this.action = action;
this.children = children;
this.conditions = conditions;
}
在这一步要将循环方法中的子token嵌套到对应的token中,以及条件渲染子token嵌套到对应token中 。
这步完成之后,一个标准的带有嵌套关系的AST完成了 。
3. 变量查找与赋值现在开始根据token中的变量查找到对应的值,根据相应功能生成值得字符串 。
/**
* 解析数据结构的类
*/
function Context (data, parentContext) {
this.data = https://www.520longzhigu.com/diannao/data;
this.cache = { ‘.’: this.data };
this.parent = parentContext;
}
Context.prototype.push = function (data) {
return new Context(data, this);
}
// 根据字符串name找到真实的变量值
Context.prototype.lookup = function lookup (name) {
name = trim(name);
var cache = this.cache;
var value;
// 查询过缓存
if (cache.hasOwnProperty(name)) {
value = https://www.520longzhigu.com/diannao/cache[name];
} else {
var context = this, names, index, lookupHit = false;
while (context) {
// user.username
if (name.indexOf(‘.’) > 0) {
value = https://www.520longzhigu.com/diannao/context.data;
names = name.split(‘.’);
index = 0;
while (value != null && index < names.length) {
if (index === names.length – 1) {
lookupHit = hasProperty(value, names[index]);
}
value = https://www.520longzhigu.com/diannao/value[names[index++]];


以上关于本文的内容,仅作参考!温馨提示:如遇健康、疾病相关的问题,请您及时就医或请专业人士给予相关指导!

「四川龙网」www.sichuanlong.com小编还为您精选了以下内容,希望对您有所帮助: