【问题标题】:Unable to extends the base templates Django无法扩展基本模板 Django
【发布时间】:2019-01-21 06:23:00
【问题描述】:

我创建了一个包含以下内容的 base.html。 yarnMMS/templates/my/base.html

{% load staticfiles %}
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>Yarn Management System</title>
</head>
<body>
<div class="content-page">

        <!-- Start content -->

        {% block content %}
        {% endblock  %}
        <!-- END content -->

    </div>
</body>
</html>

现在我正在尝试扩展我的 base.html 。 yarnMMS/templates/my/content.html

{% extends 'my/base.html' %}
{% block content %}
 <h1>Content Block</h1>
{% endblock %}

但我没有得到所需的结果。所以请指出错误。

这是我的 settings.py,我在其中添加了模板目录。

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',
            ],
        },
    },
] 

【问题讨论】:

  • base.html 在哪里?它是否在应用的模板文件夹中?
  • 是的,它在应用文件夹模板中。
  • 你能用应用的目录结构更新你的问题吗?
  • 已更新。请立即查看

标签: django django-templates django-views


【解决方案1】:

为了在应用程序中扩展和继承模板,您需要将其名称提供给标签。

这应该可行:

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

如果它位于项目的 templates 目录中的另一个文件夹中,只需提供文件夹名称:

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

【讨论】:

  • 它在项目目录中。不在App目录中。
  • @HassanALi 是的,只需提供包含文件夹的名称。
  • {% extends 'templates/my/base.html' %} like this
  • @HassanALi {% extends 'my/base.html' %}.
  • 抱歉,没有成功。
【解决方案2】:

您可以在settings.py 中将标记为TEMPLATES 的部分添加到您的问题中。但是请检查以下内容,这可能是问题所在。

确保在您的settings.py 模块中,TEMPLATES 设置中存在以下行:

...
TEMPLATES = [
             ...
             'DIRS': [
                 os.path.join(BASE_DIR, 'templates'),
             ],
             ...
]
...

这告诉 django 在那个目录中寻找模板,在本例中是在项目的基本目录BASE_DIR 中的templates 目录,你可以添加任意数量的模板,只要确保将它们添加到DIRS设置并指定磁盘上的位置,然后在模板中调用它们!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-28
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 2010-11-27
    • 1970-01-01
    相关资源
    最近更新 更多