从 jinja 模板访问字典数据

accessing dictionary data from jinja template

我有一个 dictionary 在我的视图中,想在我的前端呈现它的所有数据。

我的views.py:

def index(request):
    leafVsImdtParents = {
        100: [{'childId': 1, 'childStructure': 'Leaf'}, {'childId': 2, 'childStructure': 'Intermediate'}],
        200: [{'childId': 3, 'childStructure': 'Intermediate'}, {'childId': 4, 'childStructure': 'Leaf'}],
        300: [{'childId': 5, 'childStructure': 'Leaf'}, {'childId': 6, 'childStructure': 'Intermediate'}],
        400: [{'childId': 7, 'childStructure': 'Intermediate'}, {'childId': 8, 'childStructure': 'Leaf'}],
    }
    return render(request,'index.html', {'leafVsImdtParents ': leafVsImdtParents })

在我的 templete:

<tbody>
    {% for key, value in leafVsImdtParents %}
    <tr>
        <td>
            {% if key != 0 %}
            <a href="{% url 'diagnosis:ruleTree' ruleId=key %}" class="text-dark fw-bolder text-hover-primary d-block fs-6">
                <span class="badge badge-light-info fs-7"> {{ key }} </span>
            </a>
            {% else %}
            <span class="badge badge-light-danger"> Root Node! </span>
            {% endif %}
        </td>
        <td>
            {% for j in value %}
            <a href="">
                {% if j.childStructure == 'Leaf' %}
                <span class="badge badge-light-success fs-7"> {{ j.childId }} </span>
                {% else %}
                <span class="badge badge-light-info fs-7"> {{ j.childId }} </span>
                {% endif %}
            </a>
            {% endfor %}
            
        </td>
    </tr>
    {% endfor %}
</tbody>

但它显示如下错误:

ValueError at /ruleTreeGroup/
Need 2 values to unpack in for loop; got 1. 

请建议我如何解决这个问题以及如何从我的前端data字典中访问所有数据

这样试试

<tbody>
    {% for key, value in leafVsImdtParents.items %} # this line is changed
    <tr>
        <td>
            {% if key != 0 %}
            <a href="{% url 'diagnosis:ruleTree' ruleId=key %}" class="text-dark fw-bolder text-hover-primary d-block fs-6">
                <span class="badge badge-light-info fs-7"> {{ key }} </span>
            </a>
            {% else %}
            <span class="badge badge-light-danger"> Root Node! </span>
            {% endif %}
        </td>
        <td>
            {% for j in value %}
            <a href="">
                {% if j.childStructure == 'Leaf' %}
                <span class="badge badge-light-success fs-7"> {{ j.childId }} </span>
                {% else %}
                <span class="badge badge-light-info fs-7"> {{ j.childId }} </span>
                {% endif %}
            </a>
            {% endfor %}
            
        </td>
    </tr>
    {% endfor %}
</tbody>