Boone Putney bio photo

Boone Putney

Software Development
Random Musings
Austin, Texas

HumanPlanet Soleer

Email LinkedIn Github

Description

Below is how we used the Django template system to render nested list items. Since there could potentially be an infinite number of levels, the best option was recursion. I’m not going to get into the discussion of whether or not you should be doing this in a view, but this is how we implemented the solution…

Code

 1 <ol class="list-group">
 2     {% for task in task_list %}
 3     <li class='task-list-item'>
 4         <!-- Display necessary task information/fields here -->
 5         {% if task.children %}
 6             {% with task_list=task.children %}
 7                 {% include "todo/task_item.html" %}
 8             {% endwith %}
 9         {% endif %}
10     </li>
11     {% endfor %}
12 </ol>

Task_List Visual

1 task_list = [...]  # List of first-level task items
2 
3 task = {
4     name: "Name",
5     other_data: "Other Value",
6     children: [...]  # List of task children following same format
7 }

Explanation

The template code resides in the “todo/task_item.html” file, and functions as follows:

  1. Code iterates through all of the task items in task_list.
  2. Outputs each task and associated layout.
  3. If the task has children:
    1. Set the task_list variable as the children of the current task.
    2. Recursive call to current template file.
    3. Output any nested children in a nested list.
    4. Repeat recursion as necessary.