【发布时间】:2018-03-26 09:04:49
【问题描述】:
在此先感谢所有可以提供帮助的人。我对 Django“模板继承”有一些奇怪的行为 - 主要问题是 (menu.html) 中的 {% extends 'base.html' %} 在目标 (base.html) 文档中没有显示任何内容。而恰恰相反 - Django 从 base.html 中获取 header 并将其加载到 (menu.html) 中,这很奇怪,考虑到继承的逻辑。
我已经阅读了所有类似的问题,尝试了不同的方法,但一无所获......无论如何 - “包含”标签与所有模板完美配合。
我在 Windows 10 上使用 Django 1.11.11 和 python 3.6.4。
让我列出文件本身:
menu.html:
{% extends 'base.html' %}
{% block title %}
Some text
{% endblock %}
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% block title %}
{% endblock %}
</body>
</html>
Urls.py
from django.conf.urls import url
from django.contrib import admin
from linguistic import views
from linguistic.views import index, menu, about, contact
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index),
url(r'^menu/$', views.menu),
url(r'^about/$', views.about),
url(r'^contact/$', views.contact),
]
Views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, 'base.html', {'foo':'bar'})
def about(request):
return render(request, 'about.html')
def contact(request):
return render(request, 'contact.html')
def menu(request):
return render(request, 'menu.html', {'foo':'bar'})
Settings.py 元素
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ROOT_URLCONF = 'linguistic.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
项目目录结构:
Django_111:
--Include
--Lib
--linguistic
-----setting.py
-----urls.py
-----views.py
--Scripts
--tcl
--templates
-----base.html
-----about.html
-----menu.html
-----contact.html
--manage.py
【问题讨论】:
-
我不清楚您正在看到什么以及您希望看到什么。如果您转到
localhost:8000/menu/,视图将呈现menu.html模板。这将采用base.html(它正在扩展的模板)并替换menu.html中的{% title %}块。所以渲染的模板将包含<body>Some text</body>。这是您看到的行为吗? -
在正文之后你必须阻止
{% block content %}{{ content }}{% endblock %}丢失,是的,同意@Alasdair -
阿拉斯代尔,嗨。我期望这种行为,但从 menu.html 继承的内容没有显示。所以 localhost:8000 (以 base.html 作为索引)什么也不显示。还尝试用绝对目录重写路径,t 也没有帮助。 Anup,尝试使用 {{ content }} - 块内有括号,但也没有显示任何内容。
-
我不确定您希望 index 显示什么,但是 base.html 中没有任何使用 foo 的内容。你为什么期望它从菜单继承?这只发生在菜单视图中。 (请忽略 Anup 关于 {{ content }} 的评论,这完全是红鲱鱼。)
-
但是你为什么会这样呢?索引视图不会渲染 menu.html,只有菜单视图会这样做。如果您转到 /,您将只能看到 base.html 中的任何内容。要查看 menu.html 中的任何内容,您需要转到呈现它的视图,即 /menu/。
标签: django django-templates django-views django-1.11 django-inheritance