2011-04-04 102 views
0

在Django的意見: -如何將包含模板的變量傳遞到包含它的模板?

if request.is_ajax(): 
    t = get_template('bar-templates.html') 
    html = t.render(Context({'edit': True, 'user':'some-user' })) 
    return HttpResponse(html) 

有兩個模板: 主模板(foo-templates.html)其中包括模板(bar-templates.html)。在上下文中edituser傳遞給bar-templates.html但是這個變量也用於foo-templates.html。在Django中,我們使用{{ edit }}來捕捉變量。由於這個變量進入bar-templates.html。我怎樣才能用這foo-templates.html

富-templates.html:

{% extends "base.html" %} 

<div class="container"> 
{{ edit }} // Here I am not getting the edit value 
    {% if edit %} // I need this edit value. But this value is in context with `bar-templates.html` 
    do something 
    {% else %} 
    do something 
    {% endif %} 
    <div class="content"> 
     {% include "bar-templates.html" %} 
    </div> 

酒吧templaes.html

{{編輯}} //這裏它給我的編輯值 這是模板,我從意見發送。

如何將included template變量值用於包含它的模板。

回答

0

如果你簡單地渲染富:

t = get_template('foo-templates.html') 
html = t.render(Context({'edit': True, 'user':'some-user' })) 

然後「富」和所包含的「酒吧」都具有相同的價值「編輯」。

我不完全瞭解你的問題,但我有答案嗎?

1

從您的其他職位,您應該修改要加入到這一細節使用:

從我可以告訴,你想一個「選擇」類添加到您的工具欄菜單。這不適合你,因爲正如gcbirzan所說,你不能將你的ajax響應的上下文放到你的基本模板中。最重要的是,你不會重新渲染基礎模板,所以它不會改變。

使用JavaScript,您可以從您的part.html中提取foo_id。由於不表明代碼,可以說你有一個隱藏的div你foo_id,<div id="foo_id" style="display:none;">foo_2</div>

現在你可以改變你的AJAX功能,這樣的事情:

$.ajax({ 
    type:'GET', 
    cache: 'false', 
    url:"/foobar/", 
    success:function(data) { 
     $('#main-content').html(data); 
     var $foo_id = $('#foo_id').val(); 
     $('#foo1>ul>li.selected').removeClass('selected'); 
     $('#'+ foo_id).addClass('selected'); 
    } 

}); 
相關問題