从 art-template 模版维护到动态加载的思考

  自己用 art-template 有些年头了,最近在培养团队学习 art-template 使用,发现有一个痛点比较难解决。

  比如有一个模版,我们可以直接写在页面中,像这样:

<script id="appbtnTemp" type="text/html">
    <div id="<%=id%>" class="appbtn" title="<%=title%>" appid="<%=appid%>" realappid="<%=realappid%>" type="<%=type%>">
        <img src="<%=imgsrc%>" alt="<%=title%>" style="width:<%=appsize%>px;height:<%=appsize%>px;">
        <span style="width:<%=appsize+10%>px;"><%=title%></span>
    </div>
</script>

  但如果这是个公用的模版,在很多页面需要用到,那就不能直接写在页面中了,不然就得复制很多份了,那就只能写到 js 文件里,做为一个公用函数。

var appbtn = template.compile(
    '<div id="<%=id%>" class="appbtn" title="<%=title%>" appid="<%=appid%>" realappid="<%=realappid%>" type="<%=type%>">'+
        '<img src="<%=imgsrc%>" alt="<%=title%>" style="width:<%=appsize%>px;height:<%=appsize%>px;">'+
        '<span style="width:<%=appsize+10%>px;"><%=title%></span>'+
    '</div>'
);

  这样子虽然解决了公用的问题,但代码就变得难以维护了,毕竟是在 js 文件里写 html 代码,代码高亮提示没了,而且都是字符串拼接,如果模版有修改,将会是一个可怕的问题。

  那有没有什么解决办法呢?我的第一个想法是把每个模版都写到独立的文件里,但在官网文档里看到浏览器版本不支持文件路径读取模版,那就自己改造下吧,让浏览器版本也支持文件加载读取模版。

  这里我的大致思路是通过 jquery 的 $.ajax() 去获取模版,读取到模版然后用 template.compile() 把模版编译成函数并储存好,如果再次调用模版,则不用重新去获取模版。

$(function(){
    var cache = {};
    var renderFile = function(path, data){
        var html;
        if(cache.hasOwnProperty(path)){
			html = cache[path](data);
		}else{
			$.ajax({
				type: 'GET',
				url: path,
				dataType: 'text',
				async: false
			}).done(function(cb){
				var render = template.compile(cb);
				html = render(data);
				cache[path] = render;
			});
		}
		return html;
    }
    renderFile('test.art', {title: '测试1'});
});

  下面是 test.art 文件

<div>
    <h1><%=title%></h1>
</div>

  代码实现整体还是很 easy 的,这样修改之后,模版文件也可以统一管理了,既不会和页面混在一起,也不会和 js 混在一起。

  后续:

  在和 art-template 的作者交流后,作者给出两点解决方案:

1、如果用 webpack 结合 art-template-loader 就解决了这个问题了,它可以根据需要自动打包模板(而且是编译好的代码,不包含模板引擎)

2、我建议你使用 es6,至少模板这里可以用 es6 书写这样可以轻松的写多行字符串

posted @ 2017-05-23 18:26  胡尐睿丶  阅读(2221)  评论(2编辑  收藏  举报