P
P
polkabana2015-05-24 12:44:26
Django
polkabana, 2015-05-24 12:44:26

How to output defaultdict element by element in Django template?

We have the following code:

from collections import defaultdict

foo = defaultdict(dict)

foo[1][1] = 12
foo[1][2] = 24
foo[2][1] = 36
foo[2][2] = 48
foo[3]['string'] = 'foo bar'

print foo[2][1]
print foo[3]['string']

The prints output what they want (48 and 'foo bar'). Now I would like to display in the template using constructions like {{ foo[1][3] }} (this is not possible, I know). {{ foo.1.3 }} won't work either. How? There must be an option.
If collections in any way, I'm ready to consider other options. The task is reduced to filling a two-dimensional array and its output in a template. Looping through all elements is unfortunately not an option. You need a direct access to the index.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Filimonov, 2015-05-24
@polkabana

Create a custom filter that gets an element from a dict.

@register.filter
def get_item(v, a):
    return v.get(a)

Now in the template you can do (or even use variables for this):
ps But why is there a defaultdict, and indeed a dict? Why not list?

A
Alexey, 2015-05-24
@MAKAPOH

As far as I know, there is no way in the standard template engine, in this case you need to write your own template label . Or use the jinja templating engine , whose official support has recently appeared.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question