Login

Get dict's associated value filter

Author:
zalun
Posted:
April 2, 2009
Language:
HTML/template
Version:
Not specified
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. Bootstrap Accordian by Netplay4 5 years, 2 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 8 years, 2 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 8 years, 2 months ago
  4. Reusable form template with generic view by roldandvg 8 years, 3 months ago
  5. Pagination Django with Boostrap by guilegarcia 8 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.