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>
              <span class="icon-entity{{getEntityCat details}}">F</span>
              <span class="icon-checkbox{{getCheckStatus checked details}}"></span>
              <span class="name">{{name}}</span>
              {{> lists}}
  <article class="trees-wrapper">
    {{> lists}}

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

评论 抢沙发

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