Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

python - Accessing a dict by variable in Django templates?

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']

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>

And I'd like this to output:

<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> 

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...