2

I need to make a table in a Django template with variable columns, and I've been trying to do so by using the following code:

Suppose I have headers like :

headers = ['date', 'a', 'b', 'c']
body = [{'date': '2015-10-16', 'a':1, 'b':2, 'c':3},
        {'date': '2015-10-17', 'a':4, 'b':5, 'c':6},
        ....]

As you can see headers correspond to keys of the body values. So I've been trying to do that using for nested loops but, I failed.

<table >
    <thead>
      <tr>
         {% for th in headers %}
           <th>{{th}}</th>
         {% endfor %}
      </tr>
    </thead>
    <tbody>
      {% for bd in body  %}
       <tr>
        {% for h in header  %}
         {% with h as key %}
         <td>{{bd.key}}</td>
         {% endwith %}
        {% endfor %}
       </tr>
      {% endfor %}
    </tbody>
</table>

The {{bd.key}} is not displaying. Any solution ? or I need to rework my table.

1 Answer 1

1

Write a custom template filter:

from django.template.defaulttags import register

@register.filter
def get_dict_item(target_dict, key):
    return target_dict.get(key, '')

usage:

<table>
    <thead>
      <tr>
         {% for th in headers %}
           <th>{{ th }}</th>
         {% endfor %}
      </tr>
    </thead>
    <tbody>
      {% for bd in body  %}
       <tr>
        {% for h in header  %}
         {% with h as key %}
         <td>{{ bd|get_dict_item:key }}</td>
         {% endwith %}
        {% endfor %}
       </tr>
      {% endfor %}
    </tbody>
</table>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I was even having problems with headers containing spaces and your custom filter did it. cool.
I'm trying to use the same code but I am not shown any value for any key, though I get at the beginning of the rendered template {‰ load custom_filter ‰} - where custom_filter.py is the file containing the template custom filter. How could that be possible?

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.