views:

406

answers:

1

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 single 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

+6  A: 

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.

Felix Kling
A custom tag would be way more elegant, but I can confirm that the `with` and `include` tag work together this way.
Gregor Müllegger
Hey Felix. Cheers. That works. This is my first template so at least I can move on. But you're both right, I need to have a look at the custom template tag, once I've got the basics in my head. Really appreciated.
alj