1

i made a nested list and from that id like to make a table in my template

list looks something like

ground_skills_available = [[category1, [skill1, skill2, skill3]], [category1, [skill1, skill2]]]

Now i want to list it that you got category with below the items, next category and other items. Problem is, i have no clue about hot to show only category, instead of category +all items, since you cant seem to use the index of a list?

Can someone please help me out?

<table>
    {% for categories in ground_skills_available %}
        {% for category in categories %}
        <tr>
            <td>{{ category }}</td>
        </tr>
            {% for skill in category %}
            <tr>
                <td>{{ skill.name }}</td>
            </tr>
            {% endfor %}
        {% endfor %}
{% endfor %}

2 Answers 2

3

Change your outer loop to

{% for category, skills in ground_skills_available %}

This technique is described in the Django for loop docs.

On the first iteration of the loop, this will take the list [category1, [skill1, skill2, skill3], and assign

category = category1
skills = [skill1, skill2, skill3]

You can then display {{ category }}, and loop through skills.

Putting that together, you have:

<table>
    {% for category, skills in ground_skills_available %}
        <tr>
            <td>{{ category }}</td>
        </tr>
        {% for skill in skills %}
        <tr>
            <td>{{ skill.name }}</td>
        </tr>
        {% endfor %}
    {% endfor %}
</table>
Sign up to request clarification or add additional context in comments.

1 Comment

Ill take a look at this one, never hurts to know more possible answers for 1 question :)
2

{% if forloop.index == 1 %} ... some code ... {% endif %}

or

{% if forloop.index0 == 0 %} ... some code ... {% endif %}

Expectation:

{% for categories in ground_skills_available %}

    {% for category in categories %}
    {% if forloop.first %}
    <tr>
        <td>{{ category }}</td>
    </tr>
    {% else %}
        {% for skill in category %}
        <tr>
            <td>{{ skill.name }}</td>
        </tr>
        {% endfor %}
     {% endif %}
    {% endfor %}

{% endfor %}

1 Comment

Thanks, i was just about to ask how i should implement it cause i couldnt get it working. But this works perfectly

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.