最简单的JS模版引擎
2017-07-26 02:36
399 查看
出于某些原因,比方说学习JS模版引擎的工作原理,相信下边来自 John Resig 的一个JS function能帮助到我们。
使用起来也就三步走。
第一步,将上边的代码粘贴到JS作用域最开始部分。
第二步,随便写一个模版。
第三布,按照格式
TEMPLATE_HTML_TEXT 工作方式
TEMPLATE_HTML_ID 工作方式
慢慢领悟,很有意思。
// Simple JavaScript Templating // John Resig - https://johnresig.com/ - 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("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn( data ) : fn; }; })();
使用起来也就三步走。
第一步,将上边的代码粘贴到JS作用域最开始部分。
第二步,随便写一个模版。
<script id="hello_template"> <h2><%=message%></h2> <ul> <% for(var userIndex in users) { %> <li>#<%=users[userIndex]._id%>: <%=users[userIndex].name%></li> <% } %> </ul> </script>
第三布,按照格式
tmpl(TEMPLATE_HTML_ID | TEMPLATE_HTML_TEXT, INPUT_DATA)调用模版。
TEMPLATE_HTML_TEXT 工作方式
var html = tmpl('<h1><%=message%></h1>', {message: 'hello'}); console.log(html);
TEMPLATE_HTML_ID 工作方式
var html = tmpl('hello_template', { message: 'hello, world.', users: [ {_id: 0, name: 'robin'}, {_id: 1, name: 'alex'} ] }); console.log(html);
慢慢领悟,很有意思。
相关文章推荐
- 最简单的基于js实现的模版引擎
- MGTemplateEngine 模版引擎简单使用(转)
- 推荐一个图片管理的html模版和简单的js交互
- js模版引擎handlebars.js实用教程——each-基本循环使用方法
- js模版引擎是做什么用的?
- js模版引擎handlebars.js实用教程――为什么选择Handlebars.js
- 自定义简单的PHP模版引擎
- js模版引擎handlebars.js
- 介绍一款js模版引擎handlebars
- MGTemplateEngine 模版引擎简单使用
- js模版引擎handlebars.js
- 模仿angularjs写了一个简单的HTML模版和js数据填充的示例
- 自己写一个简单的模版引擎 推荐
- template模版引擎的使用(underscore.js)
- js模版引擎。
- 模版引擎之简单实现
- 自创的 TplTool,一个简单易用的前端模版JS组件(2016年小小成果)
- 实现一个最简单的模版引擎
- JavaScript页面模版引擎handlebars.js学习及使用
- 一个简单的javascript前端模版引擎