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
We can set the value of a variable in the Django template using with tag. This will output the below content. One downside of this approach is that we have to write the lines where we are accessing the variable inside with and endwith block. Using with is useful when using a costly variable multiple times.
From the documentation: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.
What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.
{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With