2010-01-21 2 views
14

여러 테이블이 포함 된 템플릿이 있습니다. 같은 방식으로이 표를 렌더링하는 하위 템플릿을 사용하고 싶습니다. 뷰에서 컨텍스트를 설정하고이를 템플릿에 전달하여 단일 테이블에서 작동하도록 할 수 있습니다. 그러나 다른 데이터에 대해 다른 테이블을 렌더링하기 위해 데이터를 어떻게 변경합니까?장고 템플릿 - '포함'템플릿의 컨텍스트 변경

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

내가 어떻게 당신이 'default_table.html'에 의해 표현 될 수있는 데이터의 두 번째 세트 있도록 전달할 것이라고는 'myview.py'에 더 많은 데이터를 추가 한 경우?

당신은 시도 할 수

ALJ

답변

29

(죄송합니다 ... 난 그냥 장고 함께 시작 해요)을 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을 만드는 것이 좋습니다.

+0

커스텀 태그가 더 우아 할지라도'with '와'include' 태그가 함께 작동한다는 것을 확인할 수 있습니다. –

+0

안녕하세요, 펠릭스. 건배. 그거야. 이것은 최소한 첫 번째 템플릿이므로 계속 진행할 수 있습니다. 하지만 당신이 맞아요, 일단 내 머리 속에 기본을 가지고, 사용자 정의 템플릿 태그를 좀 봐해야합니다. 정말 감사드립니다. – alj

+1

@ zag의 대답은 받아 들여진 것으로 표시해야합니다. 질문하는 내용이보다 세련된 방식으로 제공되기 때문입니다. –

47

당신은 withinclude 내부를 사용할 수 있습니다 :

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

documentation on include tag를 참조하십시오.