模板继承:将数据从父级传递到子级

时间:2019-09-09 15:05:57

标签: python flask jinja2

我正在尝试实现通用的html表模板。 在父模板(generic_table.html)中,我仅遍历字典列表以构建HTML表。

<table class="table " >
  <tbody>
        {% for elt in table %}
          <tr> 
            {% block table_td %}
              <td >{{ el.value }}</td>
            {% endblock %}
          </tr>
        {% endfor %}
  </tbody>
</table>

在子模板中,我想添加自定义列,例如带有编辑或删除按钮。

{% extends "generic_table.html" %}
  {% block table_td %}
  {{super()}}
    <td> <button> MY EDIT BTN </button </td>
    <td> <button> MY DELETE BTN </button </td>

  {% endblock table_td %}

它运行良好,但是要实现自定义按钮,我需要访问父循环上下文(例如,以获取当前ID)。有没有办法将数据从父模板传递到子模板?

1 个答案:

答案 0 :(得分:2)

对于这种模式,您可能需要关键字scoped来定义父块:

基本模板:

<tbody>
    {% for elt in table %}
      <tr>
          <td >{{ elt.value }}</td>
          {% block table_td scoped %}
          {% endblock %}
      </tr>
    {% endfor %}
</tbody>

子模板:

{% extends "generic_table.html" %}

{% block table_td %}
    <td> <button> MY EDIT BTN {{ elt.value }}  </button> </td>
    <td> <button> MY DELETE BTN  {{ elt.value }} </button> </td>
{% endblock %}