Django模板未正确渲染,只是在页面打印"{ % extends base % }"等内容

2 投票
1 回答
1134 浏览
提问于 2025-04-18 04:10

我正在尝试在我的本地机器上让一个非常基础的Django模板在谷歌应用引擎上运行(还没有部署,如果这有关系的话),但是我的应用似乎对模板的工作方式一无所知。它只是把 { % extends "base.html" %} 直接打印到网页上,而不是用它来加载模板,像这样:

在这里输入图片描述

不过,其他方面的视图似乎正常,因为 "{{ message }}" 至少能加载正确的内容。我感觉我只是缺少了一些简单的信息,但我不知道是什么。我看了很久的Django文档,还是搞不清楚哪里出错了。以下是相关的代码:

settings.py 的一部分:

TEMPLATE_DIRS = (
os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'hello/templates'))
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)

在 views.py 中:

from django import http
from django.shortcuts import render_to_response

def home(request):
    return render_to_response('index.html', {'message':'Hello World!'})

def form(request):
    return render_to_response('index.html', {'message':'This page will have a form.'})

在 base.html(在正确的 TEMPLATE_DIRS 路径下):

<head>
    <title>Lunar Spring</title>
    <meta charset="utf-8">
</head>
<body>

    <div class="header">
    Some Website Name
    </div>
    <div class="content">
    { % block content %}
    { % endblock % }
    </div>

</body>

在 index.html(同样在那个正确的路径下):

{ % extends "base.html" % }

{ % block content % }
    {{ message }}
{ % endblock % }

1 个回答

2

你的Django模板语法不太对,注意大括号和百分号之间的空格。

比如,把下面的内容替换成:

{ % extends "base.html" % }

改成:

{% extends "base.html" %}

撰写回答