包括来自django模板的静态文件 [英] include static files from django template
问题描述
我正在尝试从django模板中添加静态html页面。
I'm trying to include a static html page from a django template.
我尝试使用 {%include the_static.html%}
,但这并不适用于某些未知的原因。
I tried using {% include the_static.html %}
but this doesn't work for some unknown reason.
the_static.html页面是一个经常使用html编辑器修改的数据页面。
和my_model有一个url到这个html和 include
但是django拒绝找到它,虽然我确定我已经正确设置路径。
the_static.html page is a data page that will be modified often with an html editor.
and my_model has a url to this html and include
it. But django refuses to find it although I'm sure I've setup the path correctly.
推荐答案
你可以写你的自定义模板标签来执行此操作。
You can write your custom template tag to do this.
-
创建
appname / templatetags /
下的名为includestatic.py
的文件。此外,请记住创建appname / templatetags / __ init __。py
,将应用程序包括在设置中并重新启动服务器。
Create a file named
includestatic.py
underappname/templatetags/
. Also, remember to createappname/templatetags/__init__.py
, to include the app in settings and to restart the server.
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)
要在模板中使用它,请在模板顶部放置 {%load includestatic%}
,然后使用 {%includestaticapp / file.txt%}
。
这篇关于包括来自django模板的静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!