学习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)

10-05 20:49
查看更多