[Answer]-Generating complex tables with Django

1👍

You can create a new template filter that will take a value and render either the string or if it’s a list, it’ll render each item in the list.

# custom_filters.py
@register.filter(name='string_or_list')
def string_or_list(value, delimiter='\n'):
    """Renders string or each instance of a list with given delimiter."""
    if isinstance(value, list):
        return delimiter.join(value)
    return value

Then in your template you’d do:

{% load custom_filters %}
<table class="table-striped table">
    {% for row in table %}
    <tr>
        {% for item in row %}
            <td>{{ item|string_or_list }}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

Leave a comment