eug*_*ene 2 django static templates
我正在尝试从django模板中包含一个静态html页面.
我尝试过使用,{% include the_static.html %}但这不是出于某种未知原因.
the_static.html页面是一个经常使用html编辑器修改的数据页面.
和my_model有一个这个HTML的URL和include它.但是django拒绝找到它,虽然我确信我已经正确设置了路径.
您可以编写自定义模板标记来执行此操作.
创建一个名为文件includestatic.py下appname/templatetags/.此外,请记住创建appname/templatetags/__init__.py,在应用程序中包含应用程序并重新启动服务器.
includestatic.py 应该有这个代码:
from django import template
from django.contrib.staticfiles import finders
from django.utils.html import escape
register = template.Library()
@register.simple_tag
def includestatic(path, encoding='UTF-8'):
file_path = finders.find(path)
with open(file_path, "r", encoding=encoding) as f:
string = f.read()
return escape(string)
Run Code Online (Sandbox Code Playgroud)要在模板中使用它,请将其放在模板{% load includestatic %}的顶部,然后使用标记{% includestatic "app/file.txt" %}.
小智 1
我不确定我是否理解了一切......
您有一个由 Django 在给定 url 上提供的 HTML 页面,我们假设它是http://mydjangodomain/get_the_static/. 该 URL 在模型的 urls.py 中设置。好吧,这很正常。
您有一个适用于此模型的 django 模板。假设它在模板目录中定义mytemplates/mymodeltemplates/并被调用myfrontpage.html(因为 Django 模板是 html 文件)。
我猜你在 urls.py 中定义了一个 URL 来服务器该首页?我们假设它是http://mydjangodomain/get_the_front_page/
现在我不明白你的首页如何使用你的静态html。您的最终首页 html 是否需要“src”属性或类似属性的静态 URL,或者您是否需要将静态 html 包含到首页 html 中?
在第一种情况下,您已经有了 URL,http://mydjangodomain/get_the_static/因此只需使用它即可。
在第二种情况下,您不需要以前的 URL,直接使用它即可。此外,将 the_static.html 放入mytemplates/mymodeltemplates/. 那么你需要{% include "/mymodeltemplates/the_static.html" %}标签。如果这不起作用,请确保您的设置中有以下内容:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
APPLI_ROOT_PATH = "<absolute_path_to_the_application_root_on_your_server>"
TEMPLATE_DIRS = (
'%s/mytemplates' % APPLI_ROOT_PATH,
)
Run Code Online (Sandbox Code Playgroud)