2

I wonder if there's any way to do a while loop in django (I think that's what I'm after)?

What I'm trying to do is a nestled ul/li list.

The list is generated by a for loop in a for loop. But since some elements in the second for loop has more child's I want to iterate or them to and so on until all child nodes are iterated out. Only way I found so far is to have another for loop. But this seems not to generic and quite repetitive. And I need to know how many "levels" of child's there are.

This is what it look's like now:

<ul>
    {% for item in items %}
        <li>
            {{ item.name }}
            {% if item.childs %}
                <ul>
                    {% for child in item.childs %}
                        <li>{{ child.name }}</li>
                    {% endfor %}
                 </ul>
            {% endif %}
        </li>
    {% endfor %}
</ul>

Or is there a smarter way to send the data to the template? Can one do this with some kind of for/while loop?

..fredrik

3
  • I don't see how a while would change your situation. Your template seems fine IMO. Commented Mar 9, 2010 at 12:28
  • From a purely grammatical point, 'children' would be a better term than 'childs' ;-) Commented Mar 9, 2010 at 12:52
  • @voyager: Well in the second for loop each child may also contain child's. And since I don't know how many levels of child's there are (Data is user generated) I wan't to display all data including all child's child's. But as you say while probably isn't the solution: @Jon Cage: Good point! Commented Mar 9, 2010 at 12:57

3 Answers 3

5

Turn the list into an inclusion tag, then include it in itself.

Sign up to request clarification or add additional context in comments.

Comments

1

Sounds like recursion could solve your problem if you want to delve down into an 'unknown' depth of child elements? There are quite a few posts on this out on t'internet if you search...

Comments

0

Maybe think about: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#unordered-list ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.