简体   繁体   English

Django模板 - 使用模板变量访问字典值

[英]Django templating - accessing dictionary value using a template variable

This is the data coming from my views.py : 这是来自我的views.py的数据:

gradebook_data = {
    'G5A': [...],
    'G5B': [...],
    ...
}

sections = [
    ('G5A': '5-Einstein'),
    ('G5B': '5-Bohr'),
    ...
]

In my template, I want to iterate the sections and display gradebook data inside a for loop like this... 在我的模板中,我想迭代这些部分并在for循环中显示成绩簿数据for如下所示......

{% for code, section in sections %}
    <td>{{ gradebook_data.code }}</td>
{% endfor %}

This doesn't work since in Django it tries to do a dictionary lookup for gradebook_data['code'] when what I want to do is to get gradebook_data['G5A'] . 这不起作用,因为在Django它尝试对gradebook_data['code']进行字典查找时,我想要做的是获得gradebook_data['G5A']

Does anybody know a workaround or can point to my mistake? 有人知道解决方法还是可以指出我的错误? I have spent a whole day just for this already. 我已经花了整整一天时间。

This was quite easy to do with PHP's Twig templating library. 使用PHP的Twig模板库很容易做到这一点。

If you're using the Django templating system you can register a custom filter, which has been documented several times on SO for exactly this purpose. 如果你正在使用Django模板系统,你可以注册一个自定义过滤器,为了这个目的,已经在SO上记录了几次。 For example, here . 例如, 这里

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

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