我正在尝试从Django模板中包含一个静态的HTML页面。
我尝试使用{% include the_static.html %}
,但由于一些未知的原因,它无法正常工作。
the_static.html页面是一个数据页面,将经常使用HTML编辑器进行修改。
而我的模型有一个指向这个HTML的URL,并且使用include
将其包含进来。但是,尽管我确信已经正确设置了路径,但Django仍然找不到它。
我正在尝试从Django模板中包含一个静态的HTML页面。
我尝试使用{% include the_static.html %}
,但由于一些未知的原因,它无法正常工作。
the_static.html页面是一个数据页面,将经常使用HTML编辑器进行修改。
而我的模型有一个指向这个HTML的URL,并且使用include
将其包含进来。但是,尽管我确信已经正确设置了路径,但Django仍然找不到它。
您可以编写自定义模板标签来实现此功能。
Create a file named includestatic.py
under appname/templatetags/
. Also, remember to create appname/templatetags/__init__.py
, to include the app in settings and to restart the server.
includestatic.py
should have this code:
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)
To use it in your template, put {% load includestatic %}
at the top of your template, and then use the tag like {% includestatic "app/file.txt" %}
.
http://mydjangodomain/get_the_static/
。此URL在您的模型的urls.py中设置。好的,这很正常。mytemplates/mymodeltemplates/
中,名为myfrontpage.html
(因为在Django中模板是html文件)。http://mydjangodomain/get_the_front_page/
。
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,
)
有点像让死者复活,但至少在django 1.10中,这里有一个非常干净的答案:
http://www.effectivedjango.com/tutorial/static.html该页面的摘录:
简单的模板包含我们想要将Boostrap CSS添加到所有模板中,但我们希望避免重复:如果我们将其添加到每个模板中,当我们想要进行更改(例如添加另一个样式表)时,我们必须对所有文件进行更改。为了解决这个问题,我们将创建一个基本模板,其他模板将从中继承。
让我们在contacts应用程序的templates目录中创建base.html。
{% load staticfiles %}
<html>
<head>
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}"
rel="stylesheet" media="screen">
</head>
<body>
{% block content %}
{% endblock %}
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
</body>
</html>
{% extends "base.html" %}
{% block content %}
<h1>Contacts</h1>
<ul>
{% for contact in object_list %}
<li class="contact">{{ contact }}</li>
{% endfor %}
</ul>
<a href="{% url "contacts-new" %}">add contact</a>
{% endblock %}
按照这个步骤,我现在有了一个包含所有样式引用和导航栏等的base.html,因此block content
中的html仅是每个(不同的)页面的中央内容。