简体   繁体   English

在 Django 模板中按键访问字典

[英]Accessing dictionary by key in Django template

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"].所以{"key1":"value1","key2":"value2"}被传入并循环通过键,值对很好,但是我没有找到一个优雅的解决方案,可以从特定键直接在视图中访问,例如 bu json.items["key1"] 说"key1" ”。 I could use some if/then statements, but I'd rather do directly is there a way?我可以使用一些 if/then 语句,但我宁愿直接做有没有办法?

Here is looping code in the html template:这是html模板中的循环代码:

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

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 key is a variable.模板语言不提供显示json[key]的方法,其中key是一个变量。 You can write a template filter to do this, as suggested in the answers to this Stack Overflow question .您可以编写一个模板过滤器来执行此操作,正如Stack Overflow question的答案中所建议的那样。

As @Alasdair suggests, you can use a template filter.正如@Alasdair 建议的那样,您可以使用模板过滤器。 In your templatetags directory, create the following file dict_key.py :在您的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 %}

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'

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

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

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