Login

Get dict's associated value filter

Author:
zalun
Posted:
April 2, 2009
Language:
HTML/template
Version:
Not specified
Tags:
variable dict
Score:
0 (after 2 ratings)

Get the value associated with the key which may be represented by a varable

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@register.filter
def get( dict, key, default = '' ):
  """
  Usage: 

  view: 
  some_dict = {'keyA':'valueA','keyB':{'subKeyA':'subValueA','subKeyB':'subKeyB'},'keyC':'valueC'}
  keys = ['keyA','keyC']
  template: 
  {{ some_dict|get:"keyA" }}
  {{ some_dict|get:"keyB"|get:"subKeyA" }}
  {% for key in keys %}{{ some_dict|get:key }}{% endfor %}
  """

  try:
    return dict.get(key,default)
  except:
    return default

More like this

  1. is_dirty and dict of changed values by jaredthane 5 years, 11 months ago
  2. Javascript Chain Select Widget by ogo 7 years, 1 month ago
  3. Template Tag for Retrieving complex Settings by joelbitar 4 years, 5 months ago
  4. Debug data for forms by girasquid 6 years, 3 months ago
  5. Retrieve human-readable value from choices tuple or value from dict by JoeLinux 2 years, 5 months ago

Comments

jerry2801 (on October 20, 2009):

{{ some_dict.keyA }} isn simpler than {{ some_dict|get:"keyA" }}

??

#

elif (on November 6, 2009):

Yes it's simpler. But it doesn't wrok when keyA is a variable.

#

Please login first before commenting.