Opened 15 years ago

Closed 15 years ago

#12486 closed (wontfix)

Accessing dict values via a value of a variable as key — at Version 1

Reported by: uggsrock Owned by: nobody
Component: Template system Version: 1.1
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Luke Plant)

In the current release (and previous releases also) there is no way to access the value of a dict or other struct with the value of a variable as the key. For example if you want to have more than one struct you want to iterate over and get a key-value-based table with the data of other structs in it, you either have to do it manually inside the normal python code or with very ugly filters.

Here is a simple example i mentioned before:
(we have dictionary1 and dictionary2 with the same size and keys)

{% for key,value in dictionary1.items %}
<li>{{key}}: {{value}}, {{dictionary2.key}}</li>
{% endfor %}


This wouldn't work because it would search for dictionary2.key or dictionary[ "key" ] (so key is the string "key", not a variable)

But to get example working you would need it to call dictionary[ key ] whereas the key is a variable and its value would be used as a key.
Most solution with filters look this way:

@register.filter
def lookup(d, key):
    return d[key]

(took this one from http://push.cx/2007/django-template-tag-for-dictionary-access

As you see, there is just this ugly (and by the way also slow) way through filters but no real one the template engine should provide itself. Therefore i would suggest to take something like "dict[ var ]" or "dict[ inner_dict[ var ] ]" as the shortcut for the template engine to provide this usefull feature.

Change History (1)

comment:1 by Luke Plant, 15 years ago

Description: modified (diff)
Resolution: wontfix
Status: newclosed
Summary: Accessing dict values via a value of a variable as hashAccessing dict values via a value of a variable as key

This is essentially the same thing as #1495, and the lookup filter from #577

I don't know what your exact use case for this is, but it doesn't really fit with the ethos of Django's templating language. (As Adrian said on another ticket, "out of scope"). The intention is that Django's templates can be read and written by non-programmers, so complex logic should be view code or custom template tags.

(BTW, you were using 'hash' instead of 'key', which was confusing. I've corrected it now)

Note: See TracTickets for help on using tickets.
Back to Top