当前位置: 首页 > Web前端 > JavaScript

字符串-模板编译

时间:2023-03-27 14:11:09 JavaScript

模板编译编译就是将一种格式转换成另一种格式的过程。这里主要讨论模板编译。与普通字符串相比,模板字符串有很多不同之处。模板字符串可以嵌套,模板字符串内部可以使用${xxx}进行表达式计算和函数调用。这些其实就是模板编译的结果。普通的字符串编译也是字符拼接。如果在字符串中使用参数或表达式,则需要用+号连接,例如:letmarket=document.getElementById('market')letnum=5//Quantityletmoney=4//Amountmarket.innerHTML="totalsales"+num+"cupsoflemonade,totalamount:"+num*money+"yuan"用模板字符串表示会更简洁,不需要字符串拼接,直接用表达式即可里面,例如:market.innerHTML=`共售出${num}杯柠檬水,总金额:${num*money}元`普通字符串和模板字符串结果是一样的。可以说对模板字符串进行了编译,让字符串操作更加简洁。本来需要繁琐的字符串拼接,这里直接使用模板字符串就可以解决。模板字符串是如何编译的?下面我们来拆解一下模板字符串的编译过程。1.搭建模板生成函数这里是模板字符串编译框架,搭建一个编译函数,通过newFunction返回一个新函数,新函数接收一个obj对象,通过return返回最终结果。constcompile=function(template){//templatestringletresult=''returnnewFunction('obj',result)}2.定时替换不仅可以做数据校验,还可以判断传入的内容,对符合条件的内容。在这里,正则化起到了替代的作用。//compilefunctionconstcompile=function(template){//模板字符串letresult=template.replace(/{{(.+?)}}/g,(match,key)=>{return`obj.${键}`});结果=`返回“${result}”`;返回新函数('obj',结果);}//stringtemplateconsttemplate="

你好,我是{{user.name}}!{{user.age}}岁!

"//调用compile传入模板constrender=compile(template)console.log(render)outputresult:anonymous(obj){return"

你好,我是obj.user.name!obj.user.age岁!

"}这里的例子是用正则表达式匹配传入的字符串,用表达式替换成obj.user.name,obj.user.age的形式,虽然有表达式,但归根结底还是字符串,不能编译。我们需要让obj.user.name,obj.user.age动态化,并且能够通过编译。3、修改正则表达式,只需要修改正则表达式,使字符串变成上面提到的字符串拼接的形式即可。constcompile=function(template){//模板字符串letresult=template.replace(/{{(.+?)}}/g,(match,key)=>{//引号return`"+obj.${key}+"`});结果=`返回“${result}”`;返回新函数('obj',结果);}在template.replace中,替换符合条件的位置,变成字符串拼接的形式。constdata={user:{name:'hayes',age:18}}consttemplate="

你好,我是{{user.name}}!{{user.age}}岁!

"constrender=compile(template)constresult=render(data)console.log(result)传入的值已经处理完毕,下面template.replace的return其实就是把string改成了这种形式,只是渲染返回的result到页面,最终结果:完整版:constcompile=function(template){//templatestringletresult=template.replace(/{{(.+?)}}/g,(match,key)=>{//在return前后添加引号`"+obj.${key}+"`//这里变成了"

Hello,I'm"+obj.user.name+"!"+obj.user.age+"岁!

"});结果=`返回“${result}”`;返回新函数('obj',结果);}consttemplate="

你好,我是{{user.name}}!{{user.age}}岁!

"constrender=compile(template)constdata={user:{name:'hayes',age:18}}constresult=render(data)console.log(result)案例源码:https://gitee.com/wang_fan_w/es6-science-institute文章是对你有帮助,欢迎点亮星星