Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ciaoca opened this issue Jul 22, 2021 · 0 comments
Open

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

ciaoca opened this issue Jul 22, 2021 · 0 comments

Comments

@ciaoca
Copy link

ciaoca commented Jul 22, 2021

版本: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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant