【问题标题】:How to import parent template except for its overriden content in django templates?如何导入父模板,除了它在 django 模板中被覆盖的内容?
【发布时间】:2022-07-27 23:49:04
【问题描述】:

我正在尝试从子模板中的父模板扩展两个嵌套块。

事情是这样的:

父.html

{% block parentBlock %}
    <span> Foo </span>
    {% block rowBlock %}
        <button ...> Button here </button>
        <button ...> Another button here </button>
    {% endblock rowBlock %}
    
    <div> Some other content </div>
{% endblock parentBlock %}

child.html

{% extends 'parent.html' %}

{% block parentBlock %}
    {{ block.super }} # --> See note n°1 below
    {% block rowBlock %}
        {{ block.super }}
        <button ...> A third button that extends the 2 others </button>
    {% endblock rowBlock %}

    <div> Content that extends parentBlock from parent.html </div>
{% endblock parentBlock %}

Note n° 1:问题是标记为 Note 1 的 parentBlock 上的 child 的 block.super 将执行包含新 rowBlock 并附加新 rowBlock 的 super。

结果是这样的:

<span> Foo </span>
<button ...> Button here </button>
<button ...> Another button here </button>
<button ...> A third button that extends the 2 others </button>
<button ...> Button here </button>
<button ...> Another button here </button>
<button ...> A third button that extends the 2 others </button>
<div> Some other content </div>
<div> Content that extends parentBlock from parent.html </div>

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    事实证明,在我写问题时,我为 child.html 测试了一个新布局,解决了这个问题:

    child.html

    {% extends 'parent.html' %}
    
    {% block rowBlock %}
        {{ block.super }}
        <button ...> A third button that extends the 2 others </button>
    {% endblock rowBlock %}
    
    {% block parentBlock %}
        {{ block.super }}
        # Pulled the nested block outside of parent, it is computed in block.super
    
        <div> Content that extends parentBlock from parent.html </div>
    {% endblock parentBlock %}
    

    所以如果父级允许父级计算子级并显示它,则拉出子级,但不影响元素的出现顺序。

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 2014-10-17
      • 2019-08-11
      • 2023-04-03
      • 2011-07-21
      • 2013-09-18
      • 2017-08-23
      • 2011-04-28
      • 2017-07-06
      相关资源
      最近更新 更多