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

时间:2018-11-23 14:54:44

标签: python django django-templates django-views

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

views.py下的def home(request中,我添加了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>

1 个答案:

答案 0 :(得分:5)

您只能有一个上下文字典,但是字典可以具有任意数量的键/值。

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