python - Django 模板 : overriding blocks of included children templates through an extended template

标签 python django django-templates django-inheritance

我想知道是否有人知道如何处理以下古怪的模板结构:

### base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">

<head>
  <title> {% block title %} Title of the page {% endblock %} </title>
</head>

<body>
  <header>
    {% block header %}
      {% include "base/header.html" %}
    {% endblock header %}
  </header>
  {% block content %}{% endblock %}
</body>

</html>

### base/header.html
<div id="menu-bar">
  {% block nav %}
    {% include "base/nav.html" %}
  {% endblock %}
</div>

### base/nav.html
<nav id="menu">
  <ul>
    <li>
      <a href="/profile/">My Profile</a>
    </li>
    <li>
      <a href="/favs/">My Favorites</a>
    </li>
    {% block extra-content %}{% endblock %}
  </ul>
</nav>

而且,问题的核心:


### app/somepage.html
{% extends "base.html" %}
{% block content %}
  <p>Content is overridden!</p>
{% endblock %}

{% block extra-content %}
  <p>This will not show up, though...</p>
{% endblock %}

{% block nav %}
  <p>Not even this.</p>
{% endblock %}

问题是在扩展模板时,您只能覆盖在父级中声明的 block ,而不是它的任何子级。

我想我可以让 base.html 成为一个空的未使用的嵌套 block 的外壳,涵盖所有 future 的意外情况,但即使这样也能正确覆盖吗?那是唯一的方法吗?

如果您想知道为什么我有一个围绕 base.html 的双向包含/扩展工作流,我有许多子模板希望在整个项目中使用:页眉、页脚、导航、侧边栏等. 它们在整个站点的结构上都是一致的,但在许多情况下,站点的整个分割只需要其中的几个子模板。我的想法是在 templates/base 文件夹下定义子模板,并在其他地方扩展 templates/base-type1.html、templates/base-type2.html 等。每种类型只会引用所需的子模板,并根据需要覆盖它们以放置内容。

最佳答案

似乎鲜为人知的是,您可以将 with 关键字与 include 一起使用。将变量传递到包含模板的上下文中 - 您可以使用它来指定包含模板中的包含:

# base.html
<html>
    <body>
        {% block header %}{% include "header.html" %}{% endblock %}
    </body>
</html>

# header.html
# some stuff here
<div id="header">
    <img src="logo.png">
    {% include nav_tmpl|default:"navigation.html" %}
</div>

# special_page.html (uses other navigation)
{% extends "base.html" %}
{% block header %}
    {% include "header.html" with nav_tmpl="special_nav.html" %}
    # you might also want to wrap the include in an 'if' tag if you don't want anything
    # included here per default 
{% endblock %}

这种方法至少可以让您不必为了覆盖一个 block 而拥有一个额外的文件。您还可以使用 with 关键字通过更大的包含层次结构传递值。

关于python - Django 模板 : overriding blocks of included children templates through an extended template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9996428/

相关文章:

python - ValueError : shapes (1, 1) 和 (4,1) 未对齐 : 1 (dim 1) ! = 4(暗淡 0)

python - Django Q 对象(复杂查询)安全吗?

python - Django 模型表输入

javascript - 如何获取标签名称作为 Django 模板中选定/选中复选框的值

python - 使用 html5lib 或漂白剂删除 &lt;style&gt;...&lt;/style&gt; 标签的内容

python - Pandas - 计算和旋转以获得前两年的收入

python - 在 Django 中查询模型(两层深度)

python - 使用 .distinct() 时 Django ORM 多次返回相同的值

python - 遍历 Django 模板中的两个列表

python - 如何以脆皮形式在日期字段上显示日期选择器日历?