2010-01-21 17 views
14

Tengo una plantilla que incluye varias tablas. Quiero usar una sub-plantilla que represente estas tablas de la misma manera. Puedo hacer que funcione para una sola tabla, estableciendo el contexto en la vista y pasándolo a la plantilla. Pero, ¿cómo se cambian los datos para representar otra tabla para datos diferentes?Plantillas Django - Cambiar el contexto de una plantilla 'incluir'

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

Si añade más datos en el 'myview.py', ¿cómo pasarlo por lo que el segundo conjunto de datos podría ser prestados por el 'default_table.html'?

(Lo siento ... estoy empezando a cabo con Django)

ALJ

Respuesta

29

Puede probar el 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 %} 

Pero no sé si funciona, No lo intenté yo mismo.

Aviso: Si tiene que incluir esto muy a menudo, considere crear un custom template tag.

+0

Una etiqueta personalizada sería mucho más elegante, pero puedo confirmar que las etiquetas 'with' y' include' funcionan juntas de esta manera. –

+0

Hola Félix. Aclamaciones. Eso funciona. Esta es mi primera plantilla, así que al menos puedo seguir adelante. Pero ambos tienen razón, necesito echarle un vistazo a la etiqueta de plantilla personalizada, una vez que tengo los conceptos básicos en mi cabeza. Realmente apreciado. – alj

+1

@ zag la respuesta debe marcarse como aceptada ya que hace exactamente lo que se pide, de una manera más elegante –

47

Es posible utilizar with dentro include:

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

Ver también documentation on include tag.

Cuestiones relacionadas