Get dict's associated value filter

 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 4 years, 8 months ago
  2. Javascript Chain Select Widget by ogo 5 years, 10 months ago
  3. Template Tag for Retrieving complex Settings by joelbitar 3 years, 2 months ago
  4. Debug data for forms by girasquid 4 years, 12 months ago
  5. Retrieve human-readable value from choices tuple or value from dict by JoeLinux 1 year, 2 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.

#

(Forgotten your password?)