一个django可重用的应用程序,提供了使用循环模板继承的能力。
django-overextends的Python项目详细描述
创建
简介
一个django可重用的应用程序,提供overextendstemplate标记,一个 替换django的extends标记,它允许您 使用循环模板继承。
overextends的主要用例是同时重写 并在您自己的django项目中扩展其他可重用应用程序的模板。
示例
考虑以下设置模块和模板,以及应用程序 app1和app2捆绑在项目中,例如,为了:
# settings.py INSTALLED_APPS = ( "app1", "app2", "overextends", ) TEMPLATE_LOADERS = ( "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, "templates"),) <!-- myproject/app1/templates/pages/page.html --> <h1>Title</h1> {% block main %} <p>A paragraph in app1</p> {% enblock %} <footer>Copyright 2012</footer> <!-- myproject/app2/templates/pages/page.html --> {% overextends "pages/page.html" %} {% block main %} <p>A paragraph in app2, that wants to be on top of app1's main block</p> {{ block.super }} {% enblock %} <!-- myproject/templates/pages/page.html --> {% overextends "pages/page.html" %} {% block main %} {{ block.super }} <p>A paragraph in the project's template directory, under the other main blocks</p> {% enblock %}
加载pages/page.html时呈现的结果html将是:
<h1>Title</h1> <p>A paragraph in app2, that wants to be on top of app1's main block</p> <p>A paragraph in app1</p> <p>A paragraph in the project's template directory, under the other main blocks</p> <footer>Copyright 2012</footer>
要详细分析为什么要使用这种方法,它是如何工作的, 还有其他方法,请阅读我最初的博客文章: Circular Template Inheritance for Django
安装
安装django overextens的最简单方法是直接从pypi 通过运行以下命令使用pip:
$ pip install -U django-overextends
否则你可以下载django overextens并直接安装它 来源:
$ python setup.py install
项目配置
安装后,您可以将项目配置为使用 django通过将overextendsapp添加到 INSTALLED_APPS在项目的settings模块中:
INSTALLED_APPS = ( # ... other apps here ... 'overextends', )
对于django 1.9+,您必须将overextends添加到模板的内置项中键设置:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'builtins': ['overextends.templatetags.overextends_tags'], } }, ]
注意,overextends标记是由包提供的 overextends.templatetags.overextends_tags,不需要使用 {% load overextends_tags %}在模板中。就像extends 标记,overextends必须是模板中的第一个标记,因此 自动添加到django的内置模板标记中,删除 需要在每个模板中加载其标记库。