dis*_*ive 54 python django json
我将字典从我的视图传递给模板.所以{"key1":"value1","key2":"value2"}传入并循环遍历键,值对很好,但是我没有找到一个优雅的解决方案,直接从特定键的视图访问"key1",例如bu json.items ["key1"].我可以使用一些if/then语句,但我宁愿做直接有一种方法吗?
这是html模板中的循环代码:
{% for key, value in json.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
Ala*_*air 75
Django模板语言支持查找字典键,如下所示:
{{ json.key1 }}
Run Code Online (Sandbox Code Playgroud)
请参阅有关变量和查找的模板文档.
模板语言不提供显示方式json[key],其中key是变量.您可以编写模板过滤器来执行此操作,如此Stack Overflow问题的答案中所建议的那样.
为了克服这个问题,你可以尝试这样的事情:
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 %}
Run Code Online (Sandbox Code Playgroud)
小智 5
例如,发送以下字典
dict = {'name':'myname','number':'mynumber'}
意见:
return render(request, self.template_name, {'dict': dict})
要在html模板中呈现值:
<p>{{ dict.name }}</p>
它打印 'myname'
正如@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]
Run Code Online (Sandbox Code Playgroud)
然后,您可以在HTML中编写:
{% for k in json.items %}
<li>{{ k }} - {{ json.items|dict_key:k }}</li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)