开发者

Including a template does not render the variable value [duplicate]

开发者 https://www.devze.com 2023-02-21 20:50 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: how to pass the variable from included template to the template where it is included?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

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="#."&开发者_开发知识库gt;
         {% 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

This html is get included in the main.html

views.py

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

In response it will send the part.html But I am using foo_id it into main.html. main.html included the part.html But {{ foo_id }} in main.html is not giving me any value. I indicated the position by ??? But when I render whole template (not adding the html data in the div ) then it gives the proper data.

jquery

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


I don't really understand your question. I assume you mean that you want foo_id to be accessible from the AJAX request response, but that's not possible, since the page is rendered (and the context set) before the AJAX request is made, so part.html is just a template to django, and it uses the context of the main template to render the whole page. You need to manually change foo_id based on the response, in JavaScript, or fix your views (call the same function from the ajax view and the main view to get foo_id)

What confused me about your question is:

But when I render whole template (not adding the html data in the div ) then it gives the proper data.

, which I read as foo_id being set if you don't include part.html, so sorry if that's the case (even though it doesn't make sense to me...).

0

精彩评论

暂无评论...
验证码 换一张
取 消