如何在for循环中使用django模板点符号

如何在for循环中使用django模板点符号

本文介绍了如何在for循环中使用django模板点符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试检索字典键的值,并在Django模板的页面上显示该值:

  { %中的dictkey%%
< p> {{mydict.dictkey}}< / p>
{%endfor%}

(让我们说'keys'和'mydict'传递到上下文中的模板)



Django呈现页面但没有字典内容(无效模板变量)


$ b $我假设问题是它试图做mydict ['dictkey']而不是mydict [实际键IN变量dictkey ]?



谢谢!



更新
根据收到的答案,我需要补充说,我实际上正在寻找一个for循环中如何实现密钥查找。这更代表我的实际代码:

  {%for key,mydict1.items%的价值} 
< ; p为H. {{mydict2.key}}< / p>
{%endfor%}

基本上,我有两个共享相同键的字典,所以我不能做第二个的items()技巧。

解决方案

请参阅。



它创建一个自定义过滤器,当应用于具有键作为参数的字典时,使用该键查找字典并返回结果。



代码:

  @ register.filter 
def lookup(d,key):
如果键不在d:
返回无
返回d [键]

用法:

  {%for dict1.keys%} 
< p> {{dict2 | lookup:dictkey}}< / p>
{%endfor%}

注册过滤器在。



我觉得很难过,这种事情并不是内置的。


I am trying to retrieve the value of a dictionary key and display that on the page in a Django template:

{% for dictkey in keys %}
    <p> {{ mydict.dictkey }} </p>
{% endfor %}

(let's say 'keys' and 'mydict' have been passed into the template in the Context)

Django renders the page but without the dictionary contents ("Invalid template variable")

I assume the problem is that it is trying to do mydict['dictkey'] instead of mydict[actual key IN the variable dictkey]? How does one "escape" this behavior?

Thanks!

UPDATE:Based on the answers received, I need to add that I'm actually looking specifically for how to achieve a key lookup inside a for loop. This is more representative of my actual code:

{% for key, value in mydict1.items %}
    <p> {{ mydict2.key }} </p>
{% endfor %}

Basically, I have two dictionaries that share the same keys, so I can't do the items() trick for the second one.

解决方案

See this answer to a (possibly duplicate) related question.

It creates a custom filter that, when applied to a dictionary with a key as it's argument, does the lookup on the dictionary using the key and returns the result.

Code:

@register.filter
def lookup(d, key):
    if key not in d:
        return None
    return d[key]

Usage:

{% for dictkey in dict1.keys %}
    <p> {{ dict2|lookup:dictkey }} </p>
{% endfor %}

Registering the filter is covered in the documentation.

I find it sad that this sort of thing isn't built in.

这篇关于如何在for循环中使用django模板点符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 13:50