[Vuejs]-Rendering MPTT structure with open/close possibility in django template

3๐Ÿ‘

โœ…

If anyone interested in how I did it, here is a simple code:

HTML

<ul id="myUL">
    {% recursetree product.get_family %}
        <li>
            {% if node.is_leaf_node %}
                <span class="leaf">{{ node.code }}</span>
            {% else %}
                <span class="caret parent">{{ node.code }}</span>
                <ul class="nested">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>

CSS

ul, #myUL {
    list-style-type: none;
}

/* Remove margins and padding from the parent ul */
#myUL {
    margin: 0;
    padding: 0;
}

/* Style the caret/arrow */
.caret {
    cursor: pointer;
    user-select: none; /* Prevent text selection */
}

/* Create the caret/arrow with a unicode, and style it */
.caret::before {
    content: "\25B6";
    color: black;
    display: inline-block;
    margin-right: 6px;
}

/* Rotate the caret/arrow icon when clicked on (using JavaScript) */
.caret-down::before {
    transform: rotate(90deg);
}

/* Hide the nested list */
.nested {
    display: none;
}

/* Show the nested list when the user clicks on the caret/arrow (with JavaScript) */
.active {
    display: block;
}

Javascript

'use strict';

var togglers = document.getElementsByClassName("caret");
var i;

for (i = 0; i < togglers.length; i++) {
    togglers[i].addEventListener("click", function () {
        this.parentElement.querySelector(".nested").classList.toggle("active");
        this.classList.toggle("caret-down");
    });
}
๐Ÿ‘คViktor Mironov

Leave a comment