gpt4 book ai didi

python - Django 模板和 render() - 如何访问多个值

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:07 25 4
gpt4 key购买 nike

学习 Django 时我遇到了访问 2 个不同值的问题。

def home(request 下的 views.py 中,我添加了一个包含 2 个字典对象的列表,并在 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 之前,然后是 content 时才有效> 不起作用。

return render(request, 'overwatch_main_app/front_page.html', comp, context)

return render(request, 'overwatch_main_app/front_page.html', {'title': Competitive'} , context)

如何通过 render() 将超过 1 个字典值传递到我的模板

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

base.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>

最佳答案

你只能有一个上下文字典,但字典可以有任意多的键/值。

context = {
"owl": owl,
"title": "Competitive"
}
return render(request, 'overwatch_main_app/front_page.html', context)

关于python - Django 模板和 render() - 如何访问多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53448869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com