>  기사  >  웹 프론트엔드  >  JavaScript模板引擎用法实例

JavaScript模板引擎用法实例

PHPz
PHPz원래의
2016-05-16 15:50:361147검색

本文实例讲述了JavaScript模板引擎用法。分享给大家供大家参考。具体如下:

这里介绍的这个模板引擎写得短小精悍,非常值得一看

tmpl.js文件如下:

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function() {
 var cache = {};
 this.tmpl = function tmpl(str, data) {
  // Figure out if we're getting a template, or if we need to
  // load the template - and be sure to cache the result.
  var fn = 
   !/\W/.test(str) 
   ? 
   cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) 
   :
   // Generate a reusable function that will serve as a template
   // generator (and which will be cached).
   new Function(
    "obj", "var p=[],print=function(){p.push.apply(p,arguments);};" +
    // Introduce the data as local variables using with(){}
    "with(obj){p.push('" +
    // Convert the template into pure JavaScript
    str
     .replace(/[\r\t\n]/g, " ")
     .split(")[^\t]*)'/g, "$1\r")
     .replace(/\t=(.*?)%>/g, "',$1,'")
     .split("\t")
     .join("');")
     .split("%>")
     .join("p.push('")
     .split("\r")
     .join("\\'") + 
    "');}return p.join('');"
   ); // Function ends
  // Provide some basic currying to the user
  return data ? fn(data) : fn;
 };
})();

index.html文件如下:

JavaScript tmpl Use Demo

更多相关教程请访问 JavaScript教程

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.