如何隐藏django模板中的重复项 - 表?

时间:2017-01-04 11:27:37

标签: django django-templates

我有词:

my_dict = {
    '1': [],
    '2': [],
    '3': ['some_text'],
    '4': ['some_text'],
    '5': ['some_text'],
    '6': [],
    '7': ['other_text'],
    '8': []
}

我想在模板中显示:

+--------+------------------------------+
|   1    |                              |
+--------+------------------------------+
|   2    |                              |
+--------+------------------------------+
|   3    | some_text                    |
+--------+                              +
|   4    |                              |
+--------+                              +
|   5    |                              |
+--------+------------------------------+
|   6    |                              |
+--------+------------------------------+
|   7    | other_text                   |
+--------+------------------------------+
|   8    |                              |
+--------+------------------------------+

现在我有:

{% for skey, svalue in sdict.items %}
    <tr>
        <td>
            {{ skey }}
        </td>
        <td>
            {% for val in svalue %}
                {{ val }}
            {% endfor %}
        </td>
    </tr>
{% endfor %}

并输出:

+--------+------------------------------+
|   1    |                              |
+--------+------------------------------+
|   2    |                              |
+--------+------------------------------+
|   3    | some_text                    |
+--------+------------------------------+
|   4    | some_text                    |
+--------+------------------------------+
|   5    | some_text                    |
+--------+------------------------------+
|   6    |                              |
+--------+------------------------------+
|   7    | other_text                   |
+--------+------------------------------+
|   8    |                              |
+--------+------------------------------+

怎么做?

1 个答案:

答案 0 :(得分:0)

您可以将{% regroup %}标记与您的字典的转换版本以及{% ifchanged %}标记一起使用。

首先,您需要将视图中的字典转换为适用于{% regroup %}标记的字典,例如字典列表:

sdict_converted = [{"column_one": k, "column_two": v} for k, v in sdict.items()]

然后可以在您的模板中使用它,如下所示:

{% regroup sdict_converted|dictsort:"column_one" by "column_two" as grouped_sdict_converted %}

{% for group in grouped_sdict_converted %}
    {% for item in group.list %}
    <tr>
        <td>
        {{ item.column_one }}
        </td>
        {% ifchanged item.column_two %}
        <td rowspan="{{ group.list|length }}">
            {% for nested_value in item.column_two %}
                {{ value }}
            {% endfor %}
        </td>                    
        {% endifchanged %}
    </tr>
    {% endfor %}
{% endfor %}