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

时间:2010-01-21 17:53:48

标签: django include django-templates

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

**'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 个答案:

答案 0 :(得分:60)

您可以在with内使用include

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

另见documentation on include tag

答案 1 :(得分:30)

您可以尝试with template tag

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

但我不知道它是否有效,我自己也没试过。

注意:如果您经常要包含此内容,请考虑创建custom template tag

相关问题