0

While generating simple tables is really easy with django, I can't seem to figure out how to generate the complex table.

Currently my table is rendered with

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

This works well with a 2 dimensional array, laying out the data in the way that is inserted into the table variable

However, generating complex tables is stumping me. Let's say I want to print a table with a header a string and a datetime, and a string and list for objects.

table = [
   ["value/key", Datetime]
   ["value 1", [Object, Object, Object]]
]

The objects are objects that need specific parsing.

the table that is currently generated

I need the list to be internally loopable, instead of it getting formatted to list notation, without the other objects changing appearance.

3
  • Could you elaborate the question? Why can't you add another for loop? Commented Jun 13, 2014 at 11:18
  • When running another for loop it'll iterate over regular strings. Besides, the objects will need very specific formatting, so I'd need some kind of type validation. I haven't seen anything in Django that can do that. Commented Jun 13, 2014 at 11:44
  • The question is quite vague. Please share the views and models you have used. Commented Jun 13, 2014 at 11:56

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

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.