2011-04-04 63 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,所以很抱歉,如果是这种情况(即使它对我没有意义...)。