(function(window , undefined){ var cache = {}; var etic = window.etic = function (str, data){ str = str.trim() if (!cache[str] ){
var tpl = document.getElementById(str)
if (!tpl) throw 'tpl:' + str + ' is not load'
tpl = tpl.innerHTML
var fCon = 'var p = [];function __require(id){ \ return function(data){ return etic(id).apply(data,arguments);} \ };function __append(h){return p.push(h)}' while (true){ var pst = tpl.indexOf('<?') if (pst < 0) { fCon += "p.push('"+ tpl.replace(/[\r\t\n]/g, " ") +"');return p.join('');" break } var pend = tpl.indexOf('?>' ,pst) var preHtml = tpl.substr(0,pst) .replace(/[\r\t\n]/g, " ") var scCon = tpl.substring(pst+2 , pend) .replace(/\n/g,';') tpl = tpl.substr(pend+2) switch (scCon.charAt(0) ){ case '=': scCon = ";p.push("+ scCon.substr(1) +");" break case '#': scCon = ";__append(etic('"+ scCon.substr(1) +"').apply(this));" break case '*': scCon = '' break } fCon += "p.push('"+ preHtml +"');" + scCon } cache[str] = new Function('',fCon) } return data ? cache[str].apply(data) : cache[str] } })(this)
<script type=text/plain id=head>
title: <?= this.title ?>
</script>
<script type=text/plain id=ul>
<ul>
<?# head ?>
<? var h = __require(' head')
__append(h({'title': 'aaa'}))
?>
<? var i = 0 ,j = this.ul.length;
for (;i < j ;i++){
?>
<li>= <?= this.ul[i] ?></li>
<? }?>
</ul>
</script>
</body>
<script>
var dul = {ul:['a','b'] , title:'tt'}
console.log(etic('ul' ,dul))
</script>
<ul> title: tt title: aaa <li>= a</li> <li>= b</li> </ul>
还未支持异步加载....总感觉异步加载模版的话会变慢 - -! 模版的依赖应该在服务端拼装的时候能解决掉
本文介绍了一种自定义模板引擎的实现方式,包括如何解析模板字符串,处理变量、条件和循环等语法,以及如何将数据动态填充到模板中。通过具体示例展示了模板引擎的应用,如动态生成HTML元素。

716

被折叠的 条评论
为什么被折叠?



