Skip to content

在 js 中配置模板,能使用 include 吗? #640

@ciaoca

Description

@ciaoca

版本:v4.13.2
场景:树状菜单遍历
如果将模板放在页面中 <script> ,可以 include 自身的 id,达成目的。
但是需要放在公共部分,所以放在一个全局的 js 文件里,看示例 include 只有【模板ID】或者【文件路径】,能否支持传递模板变量?或者有其他方法?
示例:https://codepen.io/ciaoca/pen/RwVLpaa

使用 <script> 配置模板

<div id="box"></div>

<script id="tmp_tree" type="text/html">
<ul>
  {{each list item index}}
    <li>{{floor}}-{{item.title}}
      {{if item.children && item.children.length}}
        <% include('tmp_tree', {list: item.children, floor: floor+1}) %>
      {{/if}}
    </li>
  {{/each}}
</ul>
</script>

<script>
var data = [
  {
    title: 'a',
    children: [
      {
        title: 'a-1',
        children: [
          {
            title: 'a-1-1'
          },
          {
            title: 'a-1-2'
          }
        ]
      },
      {
        title: 'a-2'
      }
    ]
  },
  {
    title: 'b',
    children: [
      {
        title: 'b-1'
      },
      {
        title: 'b-2'
      }
    ]
  }
];
var html = template('tmp_tree', {
  list: data,
  floor: 0
});

document.getElementById('box').innerHTML = html;
</script>

在 js 中配置模板

var tmpTree = '<ul>'
  + '{{each list item index}}'
    + '<li class="floor_{{floor}}">{{floor}}-{{item.title}}'
      // + '{{if item.children && item.children.length}}'
      //   + '<% include('tmpTree', {list: item.children, floor: floor+1}) %>' // 这里怎样才能使用 include ?
      // + '{{/if}}'
    + '</li>'
  + '{{/each}}'
+ '</ul>';

var render = template.compile(tmpTree);
var html = render({
  list: data,
  floor: 0
});
console.log(html);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions