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

2024-05-29 11:17:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

def home(request下的views.py中,我添加了一个包含2个dictionary对象的列表,并在context下传递它。它工作得很好,我将在我的front_page.html模板中遍历字典,但是我还添加了一个简单的if title变量,它只在变量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()。只有当 ^{pr2}$

如何通过render()将多个字典值传递到模板

正面_页面.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>

Tags: apptitlemainrequestdefhtmlcontextlocation

热门问题