Django模板:通过扩展模板覆盖包含的子模板的块 [英] Django templates: overriding blocks of included children templates through an extended template

查看:129
本文介绍了Django模板:通过扩展模板覆盖包含的子模板的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering if anyone knows how to deal with the following quirky template structure:

### 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 %}

问题在于扩展模板时,您只能覆盖仅在父级中声明的块,而不能覆盖其任何子级.

The problem is when extending a template you can only override the blocks declared in the parent only, not any of its children.

我想我可以将base.html做成空的,未使用的嵌套块的外壳,以覆盖所有将来的意外情况,但是即使这样也可以正确覆盖吗?那是唯一的方法吗?

I suppose I could make base.html a husk of empty unused nested blocks covering all future contingencies, but would even that override properly? And is that the only way?

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

If you're wondering why I have a bi-directional include/extends workflow around base.html, I have many sub-templates that I want to get used all across the project: Headers, footers, navs, sidebars, etc. They all will be consistant in structure across the entire site, but in many cases a whole subdivision of the site will only need a few of those sub-templates. My idea was to define the sub-templates under the templates/base folder, and have templates/base-type1.html, templates/base-type2.html, etc to extend in other places. Each type would only reference the sub-templates needed, and override them to place content as needed.

推荐答案

您可以通过扩展当前包含的模板,然后添加扩展名而不是当前包含的基本模板来解决此问题.

You can solve this by extending your currently-included templates, then including the extension instead of the the currently-included base template.

这篇关于Django模板:通过扩展模板覆盖包含的子模板的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆