access dictionary with unicode keys from django template -


i have dictionary unicode keys (the dictionary being pulled mongo db). when render in template, cant access using keys since there no way generate unicode string in template (none know of)

here code: (abbreviated)

views.py

context={          'title':'mytitle',          'options'={                     u'a':u'1st option',                     u'a':u'1st option',                     u'a':u'1st option',                      u'a':u'1st option',                     u'a':u'1st option'          } }       return render(request,'trial.html',context) 

trial.html

<head>     <title>{{title}}</title> </head> <body>     {% in 'abcde' %}     <div>{{options.i}}</div> </body> 

all want show values in option in alphabetic order of keys. if can done in other way doesn't need solve unicode issue, happy. if there way ascii strings mongo, solve too.

assuming context in dict format (your's has option=). create custom templatetag sort values in options. hope helps.

# custom templatetag @register.filter def sort_by_key(options):     # output of list of tuples [('a', 'value1'), ('b', 'value2')]     return sorted(options.items(), key=lambda s: s[0])  # template {% option in options|sort_by_key %}     <!-- here key=option.0 , value=option.1 -->     <option id="{{ option.0 }}" value="{{ option.1 }}">{{ option.1 }}</option> {% endfor %} 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -