Finding Nested Points in Django Templates

According to the Django Book , the Django template system supports nested search queries:

Search points can be nested at several levels. For example, the following example uses {{person.name.upper}}, which translates to a dictionary search (person ['name']), then calls the (upper ()) method: '{{person.name.upper}} { {person.age}} years. ''

Are there any goblins with this approach that are not covered in the documentation? I have problems with nested points - here is a minimal example:

views.py:

test = [{'foo': [1, 2, 3], 'bar': [4, 5, 6]}, {'baz': [7, 8, 9]}]
ndx = 'bar'
t = loader.get_template('meh.html')
c = Context({'test': test,
             'ndx': ndx,})
return HttpResponse(t.render(c))

meh.html template:

<pre>
   {{ test }}
   {{ test.0 }}
   {{ test.0.ndx }}
</pre>

HTML Result:

<pre>
[{'foo': [1, 2, 3], 'bar': [4, 5, 6]}, {'baz': [7, 8, 9]}]
 {'foo': [1, 2, 3], 'bar': [4, 5, 6]}

</pre>

A nested dictionary key search in a list item does not return anything when I expect [4, 5, 6].

Jj

+5
4

, , , ndx , . :

{{ test.0.bar }}

, , .

...?

, , , , - , , , , . , . . , , , . ( , , , , .)

, . , , {{ foo.bar }} foo[bar] foo['bar']. , , -, django .

+8

, Django . ,

{{ test.0.ndx }}

"ndx" test.

, , . , Django .

+4

David is right: ndxhe will not be evaluated to receive a key, he will be used literally as a key. You can define a new template tag to make what you want simple here: http://www.djangosnippets.org/snippets/1412/

+1
source

I would suggest either (and I agree with David in interpreting your problem):

{{ test.0.bar }} # as david mentioned, or

ndx=test[0]['bar'] # in views
{{ ndx }} # in template
+1
source

All Articles