Python 通过 Django 模板中的键访问字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19745091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:29:28  来源:igfitidea点击:

Accessing dictionary by key in Django template

pythondjangojson

提问by disruptive

I'm passing a dictionary from my view to a template. So {"key1":"value1","key2":"value2"}is passed in and looping through key,value pairs is fine, however I've not found an elegant solution from access directly in the view from a specific key, say "key1"for example bu json.items["key1"]. I could use some if/then statements, but I'd rather do directly is there a way?

我正在将我的视图中的字典传递给模板。所以{"key1":"value1","key2":"value2"}传入并循环遍历键,值对很好,但是我还没有从特定键的视图中直接访问找到一个优雅的解决方案"key1",例如 bu json.items["key1"]。我可以使用一些 if/then 语句,但我宁愿直接使用有没有办法?

Here is looping code in the html template:

这是 html 模板中的循环代码:

{% for key, value in json.items %} 
  <li>{{key}} - {{value}}</li>
 {% endfor %}

采纳答案by Alasdair

The Django template language supports looking up dictionary keys as follows:

Django 模板语言支持查找字典键,如下所示:

{{ json.key1 }}

See the template docs on variables and lookups.

请参阅有关变量和查找的模板文档。

The template language does not provide a way to display json[key], where keyis a variable. You can write a template filter to do this, as suggested in the answers to this Stack Overflow question.

模板语言没有提供显示json[key], where keyis 变量的方法。您可以编写模板过滤器来执行此操作,如此Stack Overflow 问题的答案中所述。

回答by Deepak Verma

To overcome this problem you could try something like this:

为了克服这个问题,你可以尝试这样的事情:

def get_context_data(self, **kwargs):
    context['cart'] = []
    cart = Cart()
    cart.name = book.name
    cart.author = book.author.name
    cart.publisher = book.publisher.name
    cart.price = 123
    cart.discount = 12
    cart.total = 100
    context['cart'].append(cart)
    return context


class Cart(object):
    """
    Cart Template class

    This is a magic class, having attributes
    name, author, publisher, price, discount, total, image
    You can add other attributes on the fly
    """
    pass


By this way you can access your cart something like this:
{% for item in cart %}
    <div class="jumbotron">
    <div>
    <img src="{{item.image}}" />
    <div class="book_name"> <b>{{item.name}}</b></div>
    <div class="book_by"><i>{{item.author}}</i></div>
    <span>Rs. {{item.price}}</span> <i>{{item.discount}}% OFF </i>
    <b>Rs. {{item.total}}</b>
{% endfor %}

回答by Nandhitha Ramaraj

For example, to send the below dictionary dict = {'name':'myname','number':'mynumber'}

例如,发送以下字典 dict = {'name':'myname','number':'mynumber'}

views : return render(request, self.template_name, {'dict': dict})

意见: return render(request, self.template_name, {'dict': dict})

To render the value in html template: <p>{{ dict.name }}</p>

要在 html 模板中呈现值: <p>{{ dict.name }}</p>

It prints 'myname'

它打印 'myname'

回答by Micah Walter

As @Alasdair suggests, you can use a template filter. In your templatetagsdirectory, create the following file dict_key.py:

正如@Alasdair 所建议的,您可以使用模板过滤器。在您的templatetags目录中,创建以下文件dict_key.py

from django.template.defaultfilters import register

@register.filter(name='dict_key')
def dict_key(d, k):
    '''Returns the given key from a dictionary.'''
    return d[k]

Then, in your HTML, you can write:

然后,在您的 HTML 中,您可以编写:

{% for k in json.items %} 
  <li>{{ k }} - {{ json.items|dict_key:k }}</li>
{% endfor %}