简体   繁体   English

麻烦遍历django模板中的字典键和值

[英]trouble iterating through dictionary keys and values in django template

I am trying to iterate through a context dictionary in a template in django. 我试图遍历Django模板中的上下文字典。 So far I've been unsuccessful and I'm not understanding what it is wrong. 到目前为止,我一直没有成功,我还不明白这是怎么回事。

This is my view: 这是我的看法:

def main_view(request):
    cat_dict = {'Other': 0,
                  'Meeting': 0,
                  'Project 1': 0,
                  'Project 2': 0,
                  'Project 3': 0,
                  'Project 4': 0,
                  'Collaboration 1': 0,
                  'Collaboration 2': 0,
                  'Collaboration 3': 0,
                  'Process 1': 0
                  }
    my_dict = gCalScriptMain.gCalScript(cat_dict)
    return render(request, 'gCalData/gCalData_main.html', context=my_dict)

Instead, this is my template: 相反,这是我的模板:

{% extends "base.html" %}
{% block content %}

<div class="jumbotron index-jumbotron">
    <h1 id="main-title">gCalData</h1>
    <ul style="color:white">

      {% for k,v in my_dict.items %}
          <li>{{ k }}: {{ v }}</li>

      {% endfor %}

    </ul>

</div>

{% endblock %}

But I get nothing (not even an error). 但是我什么也没得到(甚至没有错误)。 The only thing I can do is retrieve a single value if I put this in the template: 我唯一能做的就是如果将其放在模板中则检索单个值:

{% extends "base.html" %}
{% block content %}

<div class="jumbotron index-jumbotron">
    <h1 id="main-title">gCalData</h1>
    <p style="color:white">{{ Other }}</p>

</div>

{% endblock %}

context that you give to render function is dictionary of variables you can use in template. 提供给render功能的context是可以在模板中使用的变量字典。 This means that you can use Other , Meeting , etc. 这意味着您可以使用OtherMeeting等。

If you want to use your dictionary, then you need to do 如果您想使用字典,则需要

...
return render(request, 'gCalData/gCalData_main.html', context={"my_dict": my_dict})

and then you can iterate over my_dict in template. 然后您可以遍历模板中的my_dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM