javascript简单模板引擎介绍

快乐打工仔 分类:实例代码

当前网站为了开发效率等因素,通常采用模板的方式。

本章节就通过代码实例简单介绍一下模板的实现原理,当然这里的模板是非常的简单的,和jQuery tmpl或者handlebarsjs等相比较不值得一提,但是咱们这里只是学习实现原理,来开阔一下视野和思路。

一.定义模板:

<!DOCTYPE html>
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.pipipi.net/" /> 
<title>前端教程网</title>
</head>
<body>
<div class="result"></div>
<script type="template" id="template">
  <h2>
    <a href="{{href}}">
      {{title}}
    </a>
  </h2>
  <img src="{{imgSrc}}" alt="{{title}}">
</script>
</body>
</html>

在实际应用中都是要通过ajax等方式从后台获取数据,这里我们为了方便演示,就将数据放在本地:

var data=[
  {
    title:"前端教程网一",
    href:"pipipi.net/a",
    imgSrc:"image/a.jpg"
  },
  {
    title:"前端教程网二",
    href:"pipipi.net/b",
    imgSrc:"image/b.jpg"
  },
  {
    title:"前端教程网三",
    href:"pipipi.net/c",
    imgSrc:"image/c.jpg"
  }
]

我们只要把模板中的相应部分替换为数据就可以了。

<!DOCTYPE html>
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.pipipi.net/" /> 
<title>前端教程网</title>
<script type="template" id="template">
  <h2>
    <a href="{{href}}">
      {{title}}
    </a>
  </h2>
  <img src="{{imgSrc}}" alt="{{title}}">
</script>
</head>
<body>
<div class="result"></div>
<script>
var data=[
  {
    title:"前端教程网一",
    href:"pipipi.net/a",
    imgSrc:"image/a.jpg"
  },
  {
    title:"前端教程网二",
    href:"pipipi.net/b",
    imgSrc:"image/b.jpg"
  },
  {
    title:"前端教程网三",
    href:"pipipi.net/c",
    imgSrc:"image/c.jpg"
  }
];
 
var template=document.querySelector('#template').innerHTML
    result=document.querySelector('.result'),
    index=0,len=data.length,
    fragment='';
  
for(;index<len;index++){
  fragment += template
  .replace( /\{\{title\}\}/,data[index].title)
  .replace( /\{\{href\}\}/,data[index].href)
  .replace( /\{\{imgSrc\}\}/,data[index].imgSrc);
}
result.innerHTML=fragment;
</script>
</body>
</html>

上面的代码实现了一定的替换功能,代码有没有发现有个问题,那就是图片中的title并没有被替换到,因为这里的正则表达式并没有采用全局匹配,只要将对应的代码修改如下即可:

for(;index<len;index++){
  fragment += template
  .replace( /\{\{title\}\}/g,data[index].title)
  .replace( /\{\{href\}\}/g,data[index].href)
  .replace( /\{\{imgSrc\}\}/g,data[index].imgSrc);
}

回复

我来回复
  • 暂无回复内容