Django 1.11模板继承{%extends'base.html'%}显示错误

时间:2018-03-26 09:04:50

标签: django django-templates django-views django-1.11 django-inheritance

事先,感谢所有可以提供帮助的人。我有一些Django“模板继承”的奇怪行为 - 主要问题是(menu.html)中的{%extends'base.html'%}在目标(base.html)文档中没有显示任何内容。而恰恰相反 - Django从base.html获取头部并将其加载到(menu.html)中,这很奇怪,考虑到继承的逻辑。

我已经阅读了所有相似的问题,尝试了不同的方法,但没有...无论如何 - “包含”标签与所有模板完美配合。

我在Windows 10上使用带有python 3.6.4的Django 1.11.11。

让我列出文件本身:

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

1 个答案:

答案 0 :(得分:0)

我也有这个问题 解决方案是编写“child html”的“父文件夹” ,如:

{% extends [parent_folder] / [child.html] %} 

在您的情况下,您希望从我的问题中理解,从“base.html”扩展“menu.html”
所以在“menu.html”的第一行写道:

{% extends 'templates/base.html' %}

我不明白为什么它在Django 1.11中有效,但解决方案如上:)