2012-08-07 71 views

回答

0

通常你把整個對象,然後用django模板語言迭代它。但是如果你有無關的變量,就不需要將它們組合成一個對象。他們都將在上下文對象內。

+0

感謝您的快速答覆。我是Django的新手,並擔心可能會使模板圖層使用的孔對象處於活動狀態,從而導致性能降低。這很棒,這樣你只能在模板層「重複自己」,無需枚舉3個位置(模型,模板和視圖)中的字段。 – 2012-08-07 17:35:11

3

您應該傳入整個對象,並且您將能夠正常訪問其屬性。這就是說,我會建議你使用RequestContext,尤其是如果你所指的模板是html的話。

一個例子:

from django.template import RequestContext 
from django.shortcuts import render_to_response 

# define object somehow.... 
my_object = {'some_stuff': some_value} 

def YourView(request): 
    context = RequestContext(request, { 
    'a_variable_you_would_like_to_pass': 'variable_value', 
    'obj' : my_object 
    }) 

    return render_to_response('your_template.html', context_instance = context) 

然後,裏面your_template.html ...

<div>{{ a_variable_you_would_like_to_pass }}</div> 
<div>{{ obj.some_stuff }}</div><!-- Would insert some_value -->