升级上周的js模版引擎 支持include
(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>
还未支持异步加载....总感觉异步加载模版的话会变慢 - -! 模版的依赖应该在服务端拼装的时候能解决掉
浙公网安备 33010602011771号