javascript循环渲染HTML模板,非侵入式

2023-2-9 09:34:26

前端渲染页面时, 经常会遇到渲染列表的需求,

当后端返回的一些字段的值是枚举类的时候(比如常用的status), 为了减轻服务端压力, 可以由前端js代码将数值转为文字显示. (映射表也由服务端下发)

这个js小插件纯js编写, 没有在标签中加入 v-for 之类的属性, 能够使HTML代码更纯净一些

用法参考: RepeatJs

源码: Gitee

1. 渲染innerHTML (二维列表)

1 <div class="effect table" id="tpl_repeat_inner">
2     <div class="flex-row-around tr">
3         <div class="td">{name}</div>
4         <div class="td">{age}</div>
5         <div class="td">{fav}</div>
6     </div>
7 </div>    

js:

1 let repeat = new zbRepeat();
2 let json_list = [{name:'张三', age:18, fav:1},{name:'李四', age:18, fav:2},{name:'王五', age:18, fav:3},{name:'赵六', age:18, fav:4}];
3 repeat.repeatInnerHTML('#tpl_repeat_inner', json_list);

 

2. 渲染outerHTML (二维列表)

1 <div class="effect table">
2     <div class="tpl_repeat_outer flex-row-around tr">
3         <div class="td">{name}</div>
4         <div class="td">{age}</div>
5         <div class="td">{fav}</div>
6     </div>
7 </div>

js:

 1 let repeat = new zbRepeat();
 2 let json_list = [{name:'张三', age:18, fav:1},{name:'李四', age:18, fav:2},{name:'王五', age:18, fav:3},{name:'赵六', age:18, fav:4}];
 3         
 4 function maping(obj) {
 5     let fav = '';
 6     switch (obj.fav) {
 7         case 1: fav = '篮球'; break;
 8         case 2: fav = '足球'; break;
 9         case 3: fav = '地球'; break;
10         default: fav = '语文';break;
11     }
12     obj.fav = fav;
13     return obj;
14 }
15 
16 repeat.repeatOuterHTML('.tpl_repeat_outer', json_list, maping); //循环oute

 

3. 渲染多层嵌套的HTML (多层及列表, 细节参考之前文章)

 1 <div class="effect" id="repeat_node">
 2     <div id="tpl_repeat_node">
 3         <div>{aa}</div>
 4         <div>{bb}</div>
 5         <div>{mm}</div>
 6         <div>
 7              <div class="cc">{n} : {v} : {mm}</div>
 8          </div>
 9         <div class="dd">
10             <div>{d1}</div>
11             <div>{d2}</div>
12             <div>{mm}</div>
13             <div class="d3">{x} : {y} : {mm}</div>
14         </div>
15     </div>
16 </div>
17                                

js:

 1 let repeat = new zbRepeat();
 2 let json_nest_list = [{
 3         'aa' : 'aa',
 4         'bb' : 'bb',
 5         'mm' : '1',
 6         'cc' : [
 7             {'n': 'n1', 'v' : 'v1', 'mm' : '2' },
 8             {'n': 'n2', 'v' : 'v2', 'mm' : '2' },
 9             {'n': 'n3', 'v' : 'v3', 'mm' : '2' },
10         ],
11         'dd' : {
12             'd1' : 'd1',
13             'd2' : 'd2',
14             'd3' : [
15                 {'x' : 'x1', 'y': 'y1', 'mm': '4'},
16                 {'x' : 'x2', 'y': 'y2', 'mm': '4'},
17                 {'x' : 'x3', 'y': 'y3', 'mm': '4'},
18             ],
19             'mm' : '3'
20         }
21     }];
22 let node = document.getElementById('tpl_repeat_node');
23 let html = repeat.repeatNode(node, json_nest_list);
24 nodel.innerHTML = html;
25          

 

posted @ 2023-02-09 09:56  myD  阅读(1073)  评论(0编辑  收藏  举报