1、入门实例首先我们来看一个简单模板: <script type="template" id="template"> <h2> <a href="{{href}}"> {{title}} </a> </h2> <img src="{{imgSrc}}" alt="{{title}}"> </script>其中被{{ xxx }}包含的就是我们要替换的变量。 接着我们可能通过ajax或者其他方法获得数据。这里我们自己定义了数据,具体如下:var data = [ { title: "Create a Sticky Note Effect in 5 Easy Steps with CSS3 and HTML5", href: "http://net.tutsplus.com/tutorials/html-css-techniques/create-a-sticky-note-effect-in-5-easy-steps-with-css3-and-html5/", imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/771_sticky/sticky_notes.jpg" }, { title: "Nettuts+ Quiz #8", href: "http://net.tutsplus.com/articles/quizzes/nettuts-quiz-8-abbreviations-darth-sidious-edition/", imgSrc: "https://d2o0t5hpnwv4c1.cloudfront.net/989_quiz2jquerybasics/quiz.jpg" } ];ok,现在的问题就是我们怎么把数据导入到模板里面呢?第一种大家会想到的就是采用replace直接替换里面的变量:template = document.querySelector("#template").innerHTML, result = document.querySelector(".result"), i = 0, len = data.length, fragment = "";
for ( ; i < len; i++ ) { fragment += template .replace( /{{title}}/, data[i].title ) .replace( /{{href}}/, data[i].href ) .replace( /{{imgSrc}}/, data[i].imgSrc ); }
result.innerHTML = fragment;第二种的话,相对第一种比较灵活,采用的是正则替换,对于初级前端,很多人对正则掌握的并不是很好,一般也用的比较少。具体实现如下:template = document.querySelector("#template").innerHTML, result = document.querySelector(".result"), attachTemplateToData;
// 将模板和数据作为参数,通过数据里所有的项将值替换到模板的标签上(注意不是遍历模板标签,因为标签可能不在数据里存在)。 attachTemplateToData = function(template, data) { var i = 0, len = data.length, fragment = "";
// 遍历数据集合里的每一个项,做相应的替换 function replace(obj) { var t, key, reg;
//遍历该数据项下所有的属性,将该属性作为key值来查找标签,然后替换 for (key in obj) { reg = new RegExp("{{" + key + "}}", "ig"); t = (t || template).replace(reg, obj[key]); }
return t; }
for (; i < len; i++) { fragment += replace(data[i]); }