如何将外部html加载到Django模板中的html中

时间:2017-03-16 05:35:30

标签: python django

我正在尝试将django应用程序合并到一个网站中,其中静态html占大多数。 目录结构如下。

root/
 ├ var/
 │  └ www/
 │   ├ html/
 │       ├ static
 │       │  ├style.css
 │       │  ├base.js
 │       │ 
 │       ├ web/
 │          ├head.html
 │          ├footer.html
 │          ├base.html
 │
 └ opt/
   └ django/
     ├ project/
     │
     ├ apps/
     ├ ├ views.py
       ├ template/
            ├ index.html

我想让/opt/django/template/index.html/var/www/html/web/中读取html。 我不知道如何包括。

{% include "/var/www/html/web/head.html" %}没用了。 我不想改变目录结构。

3 个答案:

答案 0 :(得分:2)

将此视为您的目录结构:

root/
 ├ var/
 │  └ www/
 │   ├ html/
 │       ├ static
 │       │  ├style.css
 │       │  ├base.js
 │       │ 
 │       ├ web/
 │          ├head.html
 │          ├footer.html
 │          ├base.html
 │
 └ opt/
   └ django/
     ├ project/
     │
     ├ apps/
     ├ ├ views.py
       ├ template/
            ├ index.html

在index.html中使用 /var/www/html/web/head.html 。 转到您的settings.py并添加:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'apps/template'),'/var/www/html/web/']
        ,
        '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',
            ],
        },
    },
]

现在转到index.html。

{% include "head.html" %}

我希望这会有所帮助。

答案 1 :(得分:0)

/var/www/html/web/添加到项目设置中模板配置字典中的DIRS选项。

https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-TEMPLATES-DIRS

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['/var/www/html/web/'], # won't work on Windows
        'APP_DIRS': True,
        'OPTIONS': {
            # ... some options here ...
        },
    },
]

然后:

{% include "head.html" %}

答案 2 :(得分:0)

您的模板可以随心所欲。您的模板目录是使用设置文件中TEMPLATES设置中的DIRS选项。 对于INSTALLED_APPS中的每个应用程序,加载程序会查找模板子目录。如果目录存在,Django会在那里查找模板。

注释

路径应该使用Unix风格的正斜杠,即使在Windows上也是如此。

android:layout_weight="1"