0

I have a key of dictionary like below:

 {% set ReportList = { 
   'T00004' : {'Title': 'Letter of Confirmation Loan'}, 
   'T00002' :{'Title': 'Repayment Schedule'},
   'T00010': {'Title': 'Letter of Hypothec'} } 
  %}

I want to loop through this dictionary but I want to keep the order of dictionary as it was without sorting, so it should be in order like this T00004, T00002, T00010. Therefore, I tried the following loop.

 {%for key in ReportList %} 
 {% set value = ReportList.get(key,{})%}
<tr class="link" onclick="CustomClickView('{{value.Title}}','Template/{{key}}')">
  <td width="10%">{{key}}</td>
  <td width="90%">{{value.Title}}</td>
</tr>
{%endfor%}

However, it result as T00002, T00004, T00010 orderly that was not as I expected above.

How I can keep the ordering of key dictionary without sorting in loop? Thanks.

Galen
  • 1,307
  • 8
  • 15
Houy Narun
  • 1,557
  • 5
  • 37
  • 86

2 Answers2

1

It is easy, you just need to pass OrderedDict into template, for example:

# .py
render("index.html", OrderedDict=OrderedDict)

# .html
{% set ReportList = OrderedDict({ 
   'T00004' : {'Title': 'Letter of Confirmation Loan'}, 
   'T00002' :{'Title': 'Repayment Schedule'},
   'T00010': {'Title': 'Letter of Hypothec'} }) 
%}

Then you can use it just like a normal OrderedDict.

Sraw
  • 18,892
  • 11
  • 54
  • 87
0
import pprint

reportList = { 
   'T00004' : {'Title': 'Letter of Confirmation Loan'}, 
   'T00002' :{'Title': 'Repayment Schedule'},
   'T00010': {'Title': 'Letter of Hypothec'} } 


pprint.pprint(reportList.items())

#  dict_items([
#   ('T00004', {'Title': 'Letter of Confirmation Loan'})
#   ('T00002', {'Title': 'Repayment Schedule'}), 
#   ('T00010', {'Title': 'Letter of Hypothec'})])

for  num,d in reportList.items():
  print(num)

# T00004
# T00002
# T00010
Fuji Komalan
  • 1,979
  • 16
  • 25
  • appologise, since the question is `jinja2` rather than `python`, how can we do it in `jinja2` context? Thanks. – Houy Narun Dec 21 '17 at 08:36
  • could you add some comment detail rather than only code, since it is a bit difficult to understand its detail what and how it works. Thanks. – Houy Narun Dec 21 '17 at 08:38