djangodjango-templatesdjango-mpttmptt

How to apply css to a three level recursive mptt tree in Django template?


I have following template for an Django-mptt tree:

{% load static i18n %}
<div id="work_tree">

{% load mptt_tags %}

<ol>
    {% recursetree piece_tree %}
        <li>
            <a href="../{{ node.id }}">{{ node.name_w_version }}</a>
            {% if not node.is_leaf_node %}
                <ul class="children">
                    <em>{{ children }}</em>
                </ul>             
            {% endif %}
        </li>
    {% endrecursetree %}
</ol>
</div>

The tree has three levels:

Level 1
   |---> Level 2
            |---> Level 3

I would like to style each level differently. What do I have to change in my template to accomplish this?


Solution

  • Each node in your template is an instance of your mptt model. Therefore, you can access it's level in your template:

    {% recursetree piece_tree %}
        <li>
            <a href="../{{ node.id }}">{{ node.name_w_version }}</a>
            {% if not node.is_leaf_node %}
                <ul class="children {% if node.level == 1 %}class_1{% elif node.level == 2 %}class_2{% endif %}">
                    <em>{{ children }}</em>
                </ul>             
            {% endif %}
        </li>
    {% endrecursetree %}