简体   繁体   中英

Accessing Specific Dictionary Values by Key in Django Template

I know to use '.' notation to access dictionary items in a template (just like this post explained), but when I try to access a particular key, it's not working. What's going wrong?

My dictionary: images[mykey] = "the value string"

Then in the template, I try to access by key but it doesn't work:

{% for x in otherdict %}
    {{ x }}
    {{ images.items.x }}
{% endfor %}

I can loop through the images dict just fine though:

{% for k,v in images.items %}
    {{ k }} -- {{ v }}
{% endfor %}

but I need to access by specific key!

You cannot do that out of the box, but you can do with a custom template tag.

Please see this old Django ticket for a possible solution, and for the reason the idea got rejected: Accessing dict values via a value of a variable as key

Very late to this party, but this might help somebody anyway. It doesn't need a template tag. You can very easily define a class that will let Django Template language do the job.

class DotDict( dict):
    def __getattr__( self, attr):
        return self[attr] # or, return self.get( attr, default_value)

This is a dict in all aspects except that you can't usefully use setattr on it, because getattr is redefined to return the same as indexing it. Which means that in a Django template, you can do

{{dotdict.x}}

(the template engine catches KeyError and quietly returns the blank string, if you don't use .get to provide a default)

You can convert an ordinary dict to a DotDict using the standard dict's init method

dotdict = DotDict( ordinary_dict)

which might be useful when defining a context for rendering.

You can inherit from Counter or other dict-like objects instead of plain dict , if you desire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM