Faster, Higher, Stronger
更快,更高,更强

Recursion in EJS and Handlebars

Once in a frontend project using handlebars as the template, I can use code like the following code snippet to realize recursion:

<script id="contentTpl" type="text/x-handlebars-template">
  {{! 通过#*inline标签定义行内partials片段,供递归使用}}
  {{#*inline "lists"}}
    {{#if details.length}}
      <ul class="lists">
        {{#each details}}
          <li data-index="{{@index}}" class="list{{getOpenStatus open}}">
            <div class="item-wrapper">
              {{#if details.length}}
                <span class="icon-toggle"></span>
              {{/if}}
              <span class="icon-entity{{getEntityCat details}}">F</span>
              <span class="icon-checkbox{{getCheckStatus checked details}}"></span>
              <span class="name">{{name}}</span>
              {{> lists}}
            </div>
          </li>
        {{/each}}
      </ul>
    {{/if}}
  {{/inline}}
  <article class="trees-wrapper">
    {{> lists}}
  </article>
</script>

So, I think probably recursion effect can also be implemented in EJS template. And after some testing, the answer is yes, and a sample code snippet is as below:

<% (function recursive(arr) { %>
  <% arr.forEach(function (item) { %>
    <span><%= item.text %></span>
    <% if (item.details && item.details instanceof Array) { %>
      <% recursive(item.details) %>
    <% } %>
  <% }) %>
<% })(data) %>
赞(0) 打赏
未经允许不得转载:峰间的云 » Recursion in EJS and Handlebars

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏