美文网首页
详解js模板引擎art template数组渲染的方法

详解js模板引擎art template数组渲染的方法

作者: 小边_leo | 来源:发表于2020-09-08 11:13 被阅读0次

数组渲染有数组对象和纯数组两种形式,我们先说数组对象,如后端返回我们接口,收到的就是一个数组。比如:

const res = [
{"name":"小明", "age":16, "marry":"单身"},
{"name":"小花","age":15, "marry":"有男朋友"},
{"name":"小胖","age":15, "marry":"有女朋友"},
{"name":"小丽","age":15, "marry":"单身"}
];

用artTemplate有个好处就是除了你的数据需要重组,其他的完全可以拿来直接用。如下

html

<div id="person"></div>
<script>
const res = [
{"name":"小明", "age":16, "marry":"单身"},
{"name":"小花","age":15, "marry":"有男朋友"},
{"name":"小胖","age":15, "marry":"有女朋友"},
{"name":"小丽","age":15, "marry":"单身"}
];
document.getElementById('person').innerHTML = template('personTemp', {data:res}); // 其实这里是把数组转为对象的形式传进的
</scrtip>

template

<script type="text/html" id="personTemp">
//写法一
{{each data}}
<li>{{index}}索引 我叫{{value.name}},今年{{value.age}}岁,{{value.marry}}</li>
{{/each}}

//写法二
{{each data item index}}
<li>{{index}}索引 我叫{{item.name}},今年{{item.age}}岁,{{item.marry}}</li>
{{/each}}
</script>

下面在看数组渲染,这是一个数组

const res = ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他'];

html

<div id="interest"></div>

js

<script>
const res = ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他'];
document.getElementById('interest').innerHTML = template('interestTemp', {data:res}); // 其实这里是把数组转为对象的形式传进的
</scrtip>

template

<script type="text/html" id="interestTemp">
//写法一
{{each data}}
<li>{{$index}}索引 我喜欢{{$value.name}}</li>
{{/each}}
  
//写法二
{{each data item index}}
<li>{{index}}索引 我喜欢{{item}}</li>
{{/each}}
</script>

就说这么多吧,其实这种模板用着挺简单的很顺手。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

网友评论

      本文标题:详解js模板引擎art template数组渲染的方法

      本文链接:https://www.haomeiwen.com/subject/wpydektx.html