Get nested dict items using Jinja2 in Flask

前端 未结 2 745
遇见更好的自我
遇见更好的自我 2020-12-15 08:03

for this dictionary with this Flask controller

projects = {
        \'life-calc\':{\'url\':\'life-calc\',
                    \'title\': \'Life Calculator\'}         


        
相关标签:
2条回答
  • 2020-12-15 08:45

    I think you want to know how access the nested dict in template

    If you think I got your question

    Generally, This is the way to access the nested dictionary items in dictionary.

    If the iterables are getting nested further just you have to increase the forloop depth level whether it is list or dict.

    Here I am giving just a generic example in my own way for your understanding

    Data:

    parent_dict = {1: {'A':'val1','B':'val2'}, 2:{'C':'val3','D':'val4'}}
    

    iteration in jinja2:

    {% for key,parent_dict_item in parent_dict.items() %}
       {% for key2, nested_value in parent_dict_item.items() %}
          <li><a href = "{{ nested_value }}">{{ nested_value }}</a> </li>
       {% endfor %}
    {% endfor %}
    

    Answer:

    <li><a href="val1">val1</a> </li>
    <li><a href="val2">val2</a> </li>
    <li><a href="val3">val3</a> </li>
    <li><a href="val4">val4</a> </li>
    
    0 讨论(0)
  • 2020-12-15 08:51

    Instead of expanding the key and value in the loop, you can also use the key to reference the item in the dict itself:

    {% for project in projects %}
      <li><a href = "{{ projects[project].url }}">{{ projects[project].title }}</a> </li>
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题