开发者

Django Templates - Changing context for an 'include' template

I have a template that includes several tables. I want to use a sub-template which renders these tables in the same way. I can get it to work for a singl开发者_开发问答e table, by setting the context in the view and passing that to the template. But how do you change the data for to render another table for different data?

**'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>

If I added more data in the 'myview.py', how would you pass it so the second set of data could be rendered by the 'default_table.html'?

(Sorry ... I'm just starting out with Django)

ALJ


You may use with inside include:

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

See also documentation on include tag.


You can try the 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 %}

But I don't know if it works, I didn't try it myself.

Notice: If you have to include this very often, consider to create a custom template tag.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜