2011-04-04 65 views
1

可能重複:
how to pass the variable from included template to the template where it is included?包括模板不會使變量值

main.html中

{% extends "new-base.html" %} 
{% block side-bar %} 
<div id="foo1"> 
    {% for foo in foo_list %} 
    {{ foo_id }} // ??? 
     {% ifequal foo.id foo_id %} 
      <li id="my-id_{{ foo.id }}" class="select"><a href="#."> 
     {% else %} 
      <li id="my-id_{{ foo.id }}" class="no-select"><a href="#."> 
     {% endifequal %} 
     {% endif %} 
    {% endfor %} 
    </ul> 
    </div> 
{% endblock side-bar %} 

{% block content %} 
<div class="content" id="main-content"> 
{% include "template/part.html" %} 
</div> 
{% endblock content %} 

part.html

這個HTML是獲得包含在main.html

views.py

if request.is_ajax(): 
    t = get_template('part.html') 
    html = t.render(Context({'foo_id': foo_id})) 
    return HttpResponse(html) 

在響應它將把part.html但是我使用foo_idmain.htmlmain.html 包括part.html{{ foo_id }}main.html沒有給我任何價值。我通過???表明了位置。但是當我渲染整個模板(不在div中添加html 數據)時,它會給出正確的數據。

jQuery的

$.ajax({ 
    type:'GET', 
    cache: 'false', 
    url:"/foobar/", 
    success:function(data) { 
     $('#main-content').html(data); 
    } 
}); 
+0

這裏沒有答案的問題的確切副本:http://stackoverflow.com/questions/5541312/how-to-pass-the-variable-from-included-template-to-the-template-where-it-is -inclu – DTing 2011-04-04 23:43:34

+1

對不起,但我需要更準確地制定問題 – 2011-04-05 00:06:35

+0

您可以編輯您的問題,使其更清楚,而不是創建一個新的帳戶,並重新發布問題。 – DTing 2011-04-05 02:11:28

回答

0

我真的不明白你的問題。我假設你的意思是你希望foo_id可以從AJAX請求響應中訪問,但這是不可能的,因爲在AJAX請求之前頁面被渲染(和上下文設置),所以part.html只是django的一個模板,它使用主模板的上下文來呈現整個頁面。您需要手動更改foo_id基於響應,在JavaScript中,或修復您的意見(稱之爲從阿賈克斯觀點相同的功能,主視圖得到foo_id)

什麼困惑我關於你的問題是:

但是當我渲染整個模板(不在div中添加html數據)時,它會給出正確的數據。

,如果您不包含part.html,我會將其設置爲foo_id,所以很抱歉,如果是這種情況(即使它對我沒有意義...)。