带有doT.js的嵌套列表(来自嵌套数组/对象)

时间:2016-01-20 11:31:43

标签: javascript jquery nested dot.js

有没有办法用doT.js生成嵌套列表?不幸的是,我的代码只遍历数组中的第一个对象(g1)并忽略所有后续对象。有没有办法用doT.js来解决这个问题?

结果如下:

G1
 T11
 T12
 T13
G2
 T21
 T22
 T23



$(document).ready(function() {
  var data_simple = {
    level1: [{
      name: 't1'
    }, {
      name: 't2'
    }, {
      name: 't3'
    }]
  };

  var data_complex = {
    level1: [{
      name: 'g1',
      data: [{
        name: 't11'
      }, {
        name: 't12'
      }, {
        name: 't13'
      }]
    }, {
      name: 'g2',
      data: [{
        name: 't21'
      }, {
        name: 't22'
      }, {
        name: 't23'
      }]
    }]
  };

  var compiled_tpl_simple = doT.template($('[data-template="simple"]').html());
  var compiled_tpl_complex = doT.template($('[data-template="complex"]').html());
  
  var result_simple = compiled_tpl_simple(data_simple);
  var result_complex = compiled_tpl_complex(data_complex);

  $('#output_simple').append(result_simple);
  $('#output_complex').append(result_complex);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/dot/1.0.3/doT.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script data-template="simple" type="text/x-dot-template">
	<strong>Beg simple</strong><br>
	{{~it.level1 :element:index}}
		{{=element.name}}<br>
	{{~}}
  <strong>End simple</strong>
</script>

<script data-template="complex" type="text/x-dot-template">
	<strong>Beg complex</strong><br>
	{{~it.level1 :group:index}}
  	  {{=group.name}}<br>
      {{~group.data :element:index}}
    	{{=element.name}}<br>
      {{~}}
	{{~}}
  <strong>End complex</strong>
</script>

<div id="output_simple">

</div>
<div id="output_complex">

</div>
&#13;
&#13;
&#13;

https://jsfiddle.net/srw2ogpz/

1 个答案:

答案 0 :(得分:2)

要解决此问题,请更改嵌套列表中的索引名称。

<script data-template="complex" type="text/x-dot-template">
<strong>Beg complex</strong><br>
{{~it.level1 :group:index}}
   {{=group.name}}<br>
   {{~group.data :element:index2}}
      {{=element.name}}<br>
   {{~}}
{{~}}
<strong>End complex</strong>
</script>