Search code examples
javascriptjqueryjtemplates

Creating tree view with jQuery jTemplates


In my app i have complex data structure in form of a tree when each item can have many child nodes. I am trying to build kind of tree view with this data with the help of jQuery jTemplates plugin. i am looking for a way to do it but i have come to a dead end and i don't know how to continue. so far i got:

{#foreach $T as item}
<div class="procsSumItem {#if $T.item.Status==3}pending{#/if}">

 <div class="itemIcon {#if $T.item.Status==3}pending{#/if}">
  <div class="taskIcon"></div>
 </div>

 <h2 class="title">{$T.item.Title}</h2>
 <span class="value">{$T.item.Value}</span>
  {#if $T.item.Nodes.length}<div class="expand"></div>{#/if}
 <div class="expandPanel hidden">
 {#foreach $T.item.Nodes as N1}
 {#if $T.N1.Nodes.length}
   <div class="groupHeader">
     <span class="groupIcon"></span>
     <span class="groupTitle">{$T.N1.Title}</span>
   </div>
        {#foreach $T.N1.Nodes as N2}
           {#if $T.N2.Nodes.length}
            {#foreach $T.N2.Nodes as N3}
                {#if $T.N3.Nodes.length}
                    //this can be very deep....
                 {#/if}
            {#/for}
          {#else}
             <ul class="recipents rgroup">
             <li class="{#if $T.b.Replied}rep{#/if}">
                <span class="user"></span>
                <span>{$T.b.Title}</span>
                <div class="arrow"></div>
                {#if $T.b.Replied}<span class="replied">Replied</span>{#/if}
             </li>
            </ul>
        {#/if}
       {#/for}
  {#else}
   <ul class="recipents">
    <li class="{#if $T.a.Replied}rep{#/if}">
         <span class="user"></span>
         <span>{$T.a.Title}</span>
         <div class="arrow"></div>
         {#if $T.a.Replied}<span class="replied">Replied</span>{#/if}   
    </li>
   </ul>
  {#/if}
 {#/for} 
   </div>
 <p class="time">{$T.item.CreatedAt}</p>
</div>
{#/for}

As you can see my problem is that in my current approach the process to find the child nodes of each item can be endless. If it helps i can return the depth of each item, so maybe i can loop this action. but i am not sure if this is the correct way.

any suggestions?


Solution

  • I would put the "node" template in a separate template and {#include} that template for each node.

    Inside that template, you could use an {#if} to determine if there are more child nodes to render and then recursively {#include} the node template again (from within the node template itself) to continue recursively rendering the nodes.

    Alternatively, you could use JavaScript to handle the recursion instead, rendering each level of node templates by passing in just the necessary data, and then assembling them together using jQuery's manipulation methods.