[Answer]-Sorting HTML table or Dictionary keys to make specific layout

1đź‘Ť

If you’re trying to ensure your columns are in a specific order, don’t expand the items’ keys and values; instead use dot notation to look up the values based on the keys. You already know which elements go in which order, so just loop through each item and access the keys in the order you need them, putting each into its appropriate column.

{% for order in orders %}
    <tr>
        {% for item in order.items %}
            <td>{{ item.title }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.quantity }}</td>
            <td>{{ item.street1 }}</td>
            <td>{{ item.street2 }}</td>
            <td>{{ item.county }}</td>
            <td>{{ item.city }}</td>
            <td>{{ item.country }}</td>
            <td>{{ item.postal }}</td>
            <td>{{ item.shipping }}</td>
        {% endfor %}
    </tr>
{% endfor %}

According to the Django documentation (https://docs.djangoproject.com/en/1.4/topics/templates/#variables) you can use the dot notation for dictionary lookups. So where you would use something like item['title'] in normal python, you access the same element via {{ item.title }} in a Django template.

Also note that if any of the values are blank, the Django templating system won’t get confused; it will gracefully ignore the empty/blank/non-existent value (so you don’t need the if construct to decide whether to access the data). Per the above linked documentation:

If you use a variable that doesn’t exist, the template system will insert the value of the TEMPLATE_STRING_IF_INVALID setting, which is set to ” (the empty string) by default.”

👤Zeb DeOs

0đź‘Ť

{% for order in orders %}
<tr>
    {% for key, value in order.items %}

    <td>
        {% if key == "title" %}
        {{order.title}}
        {% endif %}

        .............
    {% endfor %}
</tr>
{% endfor %}
👤catherine

Leave a comment