30

I'm trying to iterate a dictionary of dictionary in Django template page

       {% for (key_o, value_o) in f_values.items() %}
            <tr class="row {% cycle 'odd' 'even' %}">
                {% for (key_i, val_i) in value_o.items() %}
                    <td class="tile ">
                        {{ val_i }} 
                    </td>
                {% endfor %}    
            </tr>
        {% endfor %}

But getting the error

TemplateSyntaxError at /tree/branches/
Could not parse the remainder: '()' from 'f_values.items()'

What is causing the error?

--update

This is how i creating the f_values

        columnValues = []
        for idx_o, val_o in enumerate(results['values']):
            columnValues[idx_o] = {}
            for idx_i, val_i in enumerate(val_o):
                columnValues[idx_o][idx_i] = {}
                columnValues[idx_o][idx_i]['value'] = val_i
                name = columnNames[idx_i]
                columnValues[idx_o][idx_i]['name'] = name
                columnValues[idx_o][idx_i]['format'] = {}
                for val_f in formats:
                    if (name == val_f.Header) :
                        columnValues[idx_o][idx_i]['format']['LowerLimit'] = val_f.LowerLimit



data = {
        'f_values': columnValues,             
       }
Mithun Sreedharan
  • 49,883
  • 70
  • 181
  • 236

1 Answers1

61

You don't need to use () to call methods in templates, you can just use f_values.items. This notation works for lists, tuples, and functions.

For example, if you have these Python values:

    lst = ['a', 'b', 'c']
    di = {'a': 'a'}
    class Foo:
       def bar(self): pass
    foo = Foo()

in your template, you can access them like this:

    {{ lst.0 }}
    {{ di.a }}
    {{ foo.bar }}

For your code:

      {% for (key_o, value_o) in f_values.items %}
            <tr class="row {% cycle 'odd' 'even' %}">
                {% for (key_i, val_i) in value_o.items %}
                    <td class="tile ">
                        {{ val_i }} 
                    </td>
                {% endfor %}    
            </tr>
        {% endfor %}
Daniel Dinu
  • 1,783
  • 12
  • 16
  • What if the key has space in between? What selector needs to be used to use that key? – Vishnu Y S Jun 30 '17 at 07:45
  • 1
    @VishnuYS There is no standard solution for a key with spaces. I would try to avoid spaces and hyphens, but you can also check out this question for some workarounds: https://stackoverflow.com/questions/2970244/django-templates-value-of-dictionary-key-with-a-space-in-it – Daniel Dinu Jul 01 '17 at 08:40
  • Hi, I want to use user.has_module_perms(package_name) or user.has_perms(perm_list, obj=None) in template, how can I pass the argument to method ? – Rakesh Mishra Jun 30 '20 at 15:25