替代包含模板中的块
django-embed-template的Python项目详细描述
django嵌入模板
此包添加{% embed %}templateTag。这个标签结合了the include tag和the extends tag的功能,以允许更灵活和可扩展的模块化模板使用。受twig’s embed tag启发,此标记允许重写在包含的模板中定义的块。
要求
这个包是用django 1.8、1.9和1.10及其各自支持的python版本测试的。
安装
只需从pip:
pip install django-embed-template
然后确保将django_embed_template添加到settings.py中的INSTALLED_APPS中。
使用量
与{% extends %}不同,{% embed %}标记可以在模板中重复,不必作为第一个标记出现(本质上与{% include %}标记类似)。同样,{% embed %}默认继承上下文,并允许您使用with关键字传递其他上下文。使用only关键字只能传递显式列出的变量。
在许多情况下,{% include %}就足够了。然而,在更复杂的场景中,它有一种倾向,即创建数量成倍增长的组合模板。当包含的模板的内容本身是动态的时,通常会发生这种情况。考虑下面的例子(灵感来自twig’s documentation):
假设我们有一些base.html包含内容块。在此块中,我们要创建垂直和水平子块。假设我们有vertical.html包含两个并排的框,其中分别有{% block A %}和{% block B %},以及horizontal.html包含三个具有类似标记块的堆叠框。然后,我们的页面可能如下所示:
{% extends 'base.html' %} {% block content %} {% embed 'vertical.html' %} {% block A %}Arthur, King of the Britons{% endblock %} {% block B %}Sir Lancelot{% endblock %} {% endembed %} {% embed 'horizontal.html' %} {% block A %}Sir Bedevere the Wise{% endblock %} {% block B %}Sir Robin the Not-Quite-So-Brave-as-Sir-Lancelot{% endblock %} {% block C %} Other knights: {% embed 'horizontal.html' with background='gray' %} {% block A %}Sir Galahad the Pure{% endblock %} {% block B %}Sir Not Appearing In This Film{% endblock %} {% endembed %} {% endblock %} {% endembed %} {% endblock %}
注意,我们还嵌套了{% embed %}blocks,留下一些未指定的块,并将上下文传递给一个嵌入的模板。有关更多可能的场景,请浏览example templates。
许可证
这个包包括直接从django项目的代码派生的代码。包含的django许可证适用于这些代码片段。包含的cc0许可证适用于此项目的其余部分。
django嵌入模板更改日志
0.2.0(2016-08-20)
- 允许嵌套嵌入标记。
- 包括一组测试用例和示例。
- 修复与python 2和django 1.8+的兼容性
0.1.2(2016-08-10)
- 修复包以实际包含代码。
0.1.1(2016-07-31)
- 修复了多次嵌入同一模板的问题。
0.1.0(2016-07-30)
- 初始工作原型