簡體   English   中英

如何將外部html加載到Django模板中的html中

[英]How to load external html into html inside Django template

我正在嘗試將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" %}沒用。 我不想改變目錄結構。

將此視為您的目錄結構:

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" %}

我希望這將有所幫助。

/var/www/html/web/ DIRS到項目設置中模板配置字典中的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" %}

您的模板可以隨心所欲。 您的模板目錄是使用設置文件中TEMPLATES設置中的DIRS選項。 對於INSTALLED_APPS中的每個應用程序,加載程序會查找模板子目錄。 如果目錄存在,Django會在那里查找模板。

注意

路徑應該使用Unix風格的正斜杠,即使在Windows上也是如此。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            '/var/www/html/web/',
        ],
    },
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM