通过 Django 模板中的变量访问字典? [英] Accessing a dict by variable in Django templates?

查看:39
本文介绍了通过 Django 模板中的变量访问字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图代码基本上是这样的:

My view code looks basically like this:

context = Context() 
context['my_dict'] = {'a': 4, 'b': 8, 'c': 15, 'd': 16, 'e': 23, 'f': 42 }
context['my_list'] = ['d', 'f', 'e', 'b', 'c', 'a']

我想在我的 Django 模板中做的是:

And what I'd like to do in my Django template is this:

<ul>
{% for item in my_list %} 
  <li>{{ item }} : {{ my_dict.item }}</li>
{% endfor %} 
</ul>

我想输出:

<ul> 
  <li> d : 16 </li> 
  <li> f : 42 </li> 
  <li> e : 23 </li> 
  <li> b : 8 </li> 
  <li> c : 15 </li> 
  <li> a : 4 </li> 
</ul> 

但是通过 {{ my_dict.item }} 通过变量名引用 dict 实际上并不起作用.我怀疑它在内部执行 my_dict['item'] 而不是 my_dict[item].有什么办法可以解决这个问题吗?

But the reference to the dict by variable name via {{ my_dict.item }} doesn't actually work. I suspect it's internally doing my_dict['item'] instead of my_dict[item]. Is there any way to work around this?

推荐答案

没有内置的方法可以做到这一点,您需要编写一个简单的模板过滤器来做到这一点:http://code.djangoproject.com/ticket/3371

There's no builtin way to do that, you'd need to write a simple template filter to do this: http://code.djangoproject.com/ticket/3371

这篇关于通过 Django 模板中的变量访问字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆