template.js / artTemplate 模板引擎问题



 html


 <!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>basic-demo</title>
<script src="template-debug.js"></script>
</head>

<body>


<div id="content"></div>




<script id="test" type="text/html">
<ul>
    {{each }}
        <li>{{pinId }}</li>
    {{/each}}
</ul>
</script>





<script>
var data = [{"pinId":1,"userId":1}, {"pinId":2,"userId":2}, {"pinId":3,"userId":3}, {"pinId":4,"userId":4}];
var html = template('test', data);
document.getElementById('content').innerHTML = html;
</script>


</body>
</html>

这样的json数据怎么用,必须要下面这样吗?


 html


 <!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>basic-demo</title>
<script src="template-debug.js"></script>
</head>

<body>


<div id="content"></div>




<script id="test" type="text/html">
<ul>
    {{each list as val}}
        <li>{{val.pinId}}</li>
    {{/each}}
</ul>
</script>





<script>
var data = [{"pinId":1,"userId":1}, {"pinId":2,"userId":2}, {"pinId":3,"userId":3}, {"pinId":4,"userId":4}];
var dataList = {"list":data }
var html = template('test', dataList );
document.getElementById('content').innerHTML = html;
</script>


</body>
</html>

模板引擎 template.js JavaScript

塞巴斯蒂安 11 years, 4 months ago

你说的这个 template.js 不清楚具体是哪一个模板引擎,有文档没?

不过绝大多数的模板引擎都支持 this 来指向输入的对象,比如 {{each this}}{{/each}} ,这种方式就适合你举例中的直接返回数组的情况。不过由于我不知道你说的到底是哪个模板引擎,所以不确定是否支持这样引用。

但是,更加推荐的做法是修改一下你的数据格式,你上面的例子可以变成:


 javascript


 var html = template('test', { items: data });

如此一来模板里可以这么写了:


 html


 {{each items as item}}
    <li>{{item.pinId}}</li>
{{/each}}

Mirai answered 11 years, 4 months ago

Your Answer