美文网首页
模板引擎的理解

模板引擎的理解

作者: gigi1226 | 来源:发表于2018-08-14 01:24 被阅读0次
  • 什么是模板引擎
    • 概念 :模板引擎是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的文档
      就是将模板文件和数据通过模板引擎生成一个HTML代码
      image.png
  • 如一个简单的需求
    1.数据来自一个数组
    2.不能写死在页面里


    image.png
songs === [
   {name: '绅士', url: 'http://music.163.com/xxx', singer: '薛之谦'},
   {name: '刚刚好', url: 'http://music.163.com/yyy', singer: '薛之谦'},
   ...
]

两种方法:1.遍历拼接HTML字符串 2.遍历构造DOM对象
一个简化的模板引擎

字符串格式化
before:
var li = '<li>' + song[i].name + '-' + song[i].singer + '</li>'

after:
var li = stringFormat('<li>{0} - {1}</li>', songs[i].name, songs[i].singer)

function stringFormat(string){ // string是变量不是属性,不能使用this
    //params此时为string从1开始之后的数组
    var params = [].slice.call(arguments,1) // arguments为伪数组,数组的方法不能使用 call将arguments设为this

    var regex = /\{(\d+)\}/g  //匹配{一个或多个数字}
    //将字符串中的{n}替换为params[n]
    string = string.replace(regex,function(){
        //function的arguments[1]为字符串中的{n},arguments[0]为字符串中的{n}
        var index = arguments[1]
        console.log(arguments)
        return params[index]
    })//取代为function的返回值
    return string
}


  • 第一版模板引擎
模板文件 : var template = '<p>Hello, my name is <%name%>. I\'m <%age%> years old.</p>';

数据: var data = {
    name: "Krasimir",
    age: 29
}
/*
regex.exec 正则,遍历,匹配
exec在遍历匹配的所有字符串,遍历完后返回null,然后重新遍历
[^%>]不是%或>任一个字符
()正则里分组的意思,分组就是我要用的意思,用括号里的东西
*/
模板引擎: var formatEngine = function (tpl,data){
    var regex = /<%([^%>]+)?%>/g
    while(match = regex.exec(tpl)){ //这里=是赋值
        tpl = tpl.replace(match[0],data[match[1]])
        console.log(tpl)
    }
    return tpl
}
HTML文件:
var string = formatEngine(template,data)
console.log(string)
  • 复杂逻辑版模板引擎
    预备知识:
    new Function:根据字符串创建一个函数
var fn = new Function("num","console.log(num + 1)"
fn(1)//2
var fn = new Function("num","console.log(num + '1')"
fn(1)//11

等价于

var fn = function(num){
    console.log(num + 1);//函数体
}
fn(1) //2
  • 通过这种方法,我们可以根据字符串构造函数,包括他的参数和函数体,模板引擎最终返回一个编译好的模板,例如
return 
"<p>Hello, my name is " + 
this.name + 
". I\'m " + 
this.profile.age + 
" years old.</p>";

把所有字符串放在一个数组里,在程序的最后把他们拼接起来

var arr = []
arr.push("<p>Hello, my name is " )
arr.push(this.name)
Arr.push("i am");
Arr.push(this.proflie.age)
Arr.push("years old</p>")
return arr.join('')
//模板文件
var template = '<p>Hello, my name is <%this.name%>. I\'m <%this.profile.age%> years old.</p>'; 
//数据
var data = { 
               name: "zyn", 
               profile: { age: 29 } 
            }

var re = /<%([^%>]+)?%>/g, 
    code = 'var Arr=[];\n',//code保存函数体
    cursor = 0;//cursor游标告诉我们当前解析到了模板的哪个位置,我们需要它来遍历整个模板字符串

//函数add,负责将解析出来的代码行添加到变量code中去
//特别注意:把code包括的双引号字符进行转义,否则代码出错
/*
var func = new Function('x',"console.log(x+\"1\")")
func(1)
*/
var add = function(line){
    //转义
    code += 'arr.push("' + line.relpace(/"/g,'\\"') + '");\n'
}
while(match = regex.exec(tpl)){   
    add(tpl.slice(cursor,match.index))
    add(match[1])
    cursor = match.index + match[0].length
}

第一次while循环时
match=[ 0:“<%this.name%>", 
1:"this.name", 
index:21, 
input:"<p>Hello, my name is<%this.name%>.I'm<%this.profile.age%>years old.</p>",
length:2 
] 
=>tpl.slice(cursor,match.index) //<p>Hello, my name is
add(tpl.slice(cursor,match.index)) 
code=
"
var Arr=[];
Arr.push("<p>Hello, my name is ");
"
match[1] =>"this.name"
cursor = match.index + match[0].length //就是<%this.name%>最后一位的位置
然后依次类推循环

得到

var Arr[]; 
Arr.push("<p>Hello, my name is "); Arr.push("this.name"); 
Arr.push(". I'm "); 
Arr.push("this.profile.age") 
Arr.push("years old </p>") 
return Arr.join("") <p>Hello, my name is <%this.name%>. I'm <%this.profile.age%> years old.</p> 

this.name和this.profile.age不应该有引号

var add = function(line,js){//改变参数,占位符的内容和布尔值做参数
    //转义
    js?code += 'arr.push(' + line + ');\n':// 改动1
       code += 'arr.push("' + line.relpace(/"/g,'\\"') + '");\n'
}
while(match = regex.exec(tpl)){   
    add(tpl.slice(cursor,match.index))
    add(match[1],true) //改动2
    cursor = match.index + match[0].length
}
 }
改动1:三目运算,如果是js 就执行 code += 'Arr.push(' + line + ');\n' 否则执行 code += 'Arr.push("' + line.replace(/"/g, '\\"') + '");\n';

改动2:add(match[1],true);告诉函数add这次传入的是js.

剩下来是创建函数并执行它

return new Function(code.replace(/[\r\t\n]/g,'')).apply(data);

不需要显式的传参数给函数,使用apply方法来调用它,它会自动设定函数执行的上下文,this.name,这里this指向data对象

  • 当条件判断和循环时
var template = 'My skills:' + '<%for(var index in this.skills) {%>' + '<a href=""><%this.skills[index]%></a>' + '<%}%>'; var skills= ["js", "html", "css"] 

如果使用字符串拼接的话,代码就应该是下面的样子:

var temolate='My skills:' + 
for(var index in this.skills) { +
'<a href="">' + 
this.skills[index] +
'</a>' +
}

这里会产生一个异常,Uncaught SyntaxError: Unexpected token for。如果我们调试一下,把code变量打印出来,我们就能发现问题所在。

var Arr=[]; 
Arr.push("My skills:"); 
Arr.push(for(var index in this.skills) {); Arr.push("<a href=\"\">"); 
Arr.push(this.skills[index]); 
Arr.push("</a>"); 
Arr.push(}); 
Arr.push(""); 
return Arr.join("");

带for循环的那一行不能直接放到数组里,而是作为脚本的一部分直接运行,所以把内容添加到code变量之前还要做一个判断

最终代码

var templateEngine = function(html,option){
    var re = /<%([^%>]+)?%>/g, 
    reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, //.*任意字符一次或多次
    code = 'var r=[];\n', 
    cursor = 0;
    var add = function(line,js){
        js?(code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n'):
        (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
        return add
    }
    while(match = re.exec(html)){
        add(html.slice(cursor,match.index))
        add(match[1],true)
        cursor = match.index + match[0].length
    }
    add(html.substr(cursor,html.length - cursor)) //substr(start,length)
    code += 'return r.join("")'
    return new Function(code.replace(/[\r\t\n]/g, '')).apply(options);
}

github代码地址

相关文章

  • 模板引擎的理解

    什么是模板引擎概念 :模板引擎是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的...

  • new 一个 Function

    new Function 和 eval 的区别 一、从模板引擎 模板引擎可以怎样理解呢? 在一段 Html 文档里...

  • vue面试题大全

    vue 1、 你知道vue的模板语法用的是哪个web模板引擎的吗?说说你对这模板引擎的理解 Vue使用了Musta...

  • vue 248+个知识点(面试题)

    你知道vue的模板语法用的是哪个web模板引擎的吗?说说你对这模板引擎的理解 你知道v-model的原理吗?说说看...

  • 【SpringBoot】Thymeleaf助力Web项目

    Thymeleaf是个XML/XHTML/HTML5模板引擎,模版引擎怎么理解呢,想想jsp就可以理解。顺便声明一...

  • SpringBoot系列之集成jsp模板引擎

    SpringBoot系列之集成jsp模板引擎@[toc] 1、模板引擎简介 引用百度百科的模板引擎解释: 模板引擎...

  • laravel 5 blade

    参考Blade 模板引擎。Blade是一个模板引擎(什么叫模板引擎,参考浅谈模板引擎),文件需要采用blade.p...

  • node_模板引擎

    模板引擎 模板引擎的使用和集成,也就是视图。 什么是模板引擎模板引擎是一个页面模板根据一定得规则生成的html工具...

  • art-template模板引擎

    模板引擎 什么是模板引擎: 模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产...

  • Ajax-02

    模板引擎 模板引擎概述 作用:使用模板引擎提供的模板语法,可以将数据和 HTML 拼接起来。官方地址: https...

网友评论

      本文标题:模板引擎的理解

      本文链接:https://www.haomeiwen.com/subject/shtpbftx.html