Skip to main content
 首页 » 编程设计

python之Django 模板无法正确呈现,仅将 "{ % extends base % }"等打印到页面

2024年11月01日38arxive

我正在尝试让一个非常基本的 Django 模板在 google app engine 应用程序上运行(在我的本地机器上,如果这很重要,还没有部署),但我的应用程序表现得好像它不知道模板是如何工作的。它只是将 { % extends "base.html"%} 打印到网页,而不是像这样使用它来加载模板:

尽管如此, View 在其他方面似乎工作正常,因为“{{ 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 % } 

请您参考如下方法:

你的 django 模板语法不正确,注意花括号和百分号之间的空格。

例如替换:

{ % extends "base.html" % } 

与:

{% extends "base.html" %}