Django模板 - 更改“include”模板的上下文

23

我有一个包含多个表格的模板。我想使用一个子模板来以相同的方式呈现这些表格。我可以通过在视图中设置上下文并将其传递到模板来使其针对单个表格工作。但是如何更改数据以呈现不同数据的另一个表格?

**'myview.py'**

from django.shortcuts import render_to_response
table_header = ("First Title", "Second Title")
table_data = (("Line1","Data01","Data02"),
              ("Line2","Data03","Data03"))
return render_to_response('mytemplate.html',locals())

**'mytemplate.html'**

{% extends "base.html" %}
{% block content %}
<h2>Table 01</h2>
{% include 'default_table.html' %}
{% endblock %}

**'default_table.htm'**

<table width=97%>
<tr>
{% for title in table_header %}
<th>{{title}}</th>
{% endfor %}
</tr>
{% for row in table_data %}
<tr class="{% cycle 'row-b' 'row-a' %}">
{% for data in row %}
<td>{{ data }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
如果我在 "myview.py" 中添加了更多数据,你如何传递它以便 "default_table.html" 渲染第二组数据?(抱歉...我刚开始使用 Django) ALJ
2个回答

77

您可以在include中使用with

{% include "default_table.html" with table_header=table_header1 table_data=table_data1 %}

另请参阅 include标签的文档


35

你可以尝试使用with模板标签:

{% with table_header1 as table_header %}
{% with table_data1 as table_data %}
    {% include 'default_table.html' %}
{% endwith %}
{% endwith %}

{% with table_header2 as table_header %}
{% with table_data2 as table_data %}
    {% include 'default_table.html' %}
{% endwith %}
{% endwith %}

但我不确定它是否有效,我自己没有尝试过。

注意: 如果你需要频繁包含它,请考虑创建一个自定义模板标签


1
一个自定义标签会更加优雅,但我可以确认withinclude标签可以这样一起使用。 - Gregor Müllegger
嘿,Felix。干杯。那个有效。这是我的第一个模板,所以至少我可以继续了。但你们都是对的,一旦我掌握了基础知识,我需要看一下自定义模板标签。非常感谢。 - alj
2
@zag的回答应该被标记为接受,因为它以一种更优雅的方式完全符合要求。 - Michele Gargiulo
使用as关键字无效.. 等号有效..有效示例:{% with table_header1=table_header %} - Ebram Shehata

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接