1
0

template.js 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. // Simple JavaScript Templating
  2. // John Resig - http://ejohn.org/ - MIT Licensed
  3. var cache = {};
  4. function template(str, data){
  5. // Figure out if we're getting a template, or if we need to
  6. // load the template - and be sure to cache the result.
  7. var fn = cache[str] ||
  8. // Generate a reusable function that will serve as a template
  9. // generator (and which will be cached).
  10. new Function("obj",
  11. "var p=[],print=function(){p.push.apply(p,arguments);};" +
  12. // Introduce the data as local variables using with(){}
  13. "with(obj){p.push('" +
  14. // Convert the template into pure JavaScript
  15. str
  16. .replace(/\n/g, "\\n")
  17. .replace(/[\r\t]/g, " ")
  18. .replace(/'(?=[^%]*%>)/g,"\t")
  19. .split("'").join("\\'")
  20. .split("\t").join("'")
  21. .replace(/<%=(.+?)%>/g, "',$1,'")
  22. .split("<%").join("');")
  23. .split("%>").join("p.push('")
  24. + "');}return p.join('');");
  25. cache[str] = fn;
  26. // Provide some basic currying to the user
  27. return data ? fn( data ) : fn;
  28. };