学习Django和我在访问两个不同的值时遇到了问题。
在views.py
下的def home(request
中,我添加了一个包含2个dictionary对象的列表,并在context
下传递它它工作得很好,我将在我的front_page.html
模板中遍历字典,但是我还添加了一个简单的if title
变量,它只在我将{'title': 'Competitive'
}放在变量context
之前时才工作。
from django.shortcuts import render
# Create your views here.
owl = [
{
'title': 'Competitive'
},
{
'Team': 'Dynasty',
'Location': 'Souel Korea',
'Colors': 'Black & Gold',
},
{
'Team': 'OutLaws',
'Location': 'Houston',
'Colors': 'Green & Black',
}
]
def home(request):
context = {
"owl": owl
}
return render(request, 'overwatch_main_app/front_page.html', context, {'title': 'Competitive'})
def second(request):
return render(request, 'overwatch_main_app/about.html', {'title': 'Boom'})
我甚至尝试过将
comp = {'title': 'Competitive'}
放入comp
中。只有当我把render()
或comp
放在{'title': 'Competitive'}
之前,然后content
不起作用时,它才起作用。return render(request, 'overwatch_main_app/front_page.html', comp, context)
return render(request, 'overwatch_main_app/front_page.html', {'title': Competitive'} , context)
如何通过
content
首页.html
{% extends 'overwatch_main_app/base.html' %}
{% block content %}
<h1> OverWatch</h1>
{% for o in owl %}
<p>{{o.Team}}</p>
<p>{{o.Location}}</p>
<p>{{o.Colors}}</p>
{% endfor %}
{% endblock %}
基.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
{% if title %}
<title>OverWatch {{title}}</title>
{% else %}
<title> OverWatch </title>
{% endif %}
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
最佳答案
只能有一个上下文dict,但字典可以有任意多的键/值。
context = {
"owl": owl,
"title": "Competitive"
}
return render(request, 'overwatch_main_app/front_page.html', context)