how to pass the variable from included template to the template where it is included?

情到浓时终转凉″ 提交于 2019-12-02 18:07:51

问题


In Django Views:-

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

There is two templates: Main template (foo-templates.html) which includes the template (bar-templates.html). In context edit and user is passed to the bar-templates.html But this variable is also used in foo-templates.html. In django we used to {{ edit }} to catch the variable. Since this variable comes in bar-templates.html. How can I use this to foo-templates.html.

foo-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>

bar-templaes.html

{{ edit }} // Here It gives me the edit value This is the templates which I am sending from views.

How to use the included template variable values to the template where it get included.


回答1:


Using details from your other post, which you should edit to include into this one:

From what i can tell, you are trying to add a "selected" class to your sidebar menu. This won't work for you because as gcbirzan said, you aren't going to be able to get the context of your ajax response into your base template. On top of that you aren't going to re-render the base template so it wouldn't be changing anyways.

Using javascript you can extract the foo_id from your part.html. Since that code isn't shown, lets say you have your foo_id in a hidden div, <div id="foo_id" style="display:none;">foo_2</div>

Now you can change your ajax function to something like this:

$.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');
    }

});



回答2:


If you simply render foo:

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

then 'foo' and the included 'bar' both have the same value for 'edit'.

I don't completely understand your question, but have I answered it?



来源:https://stackoverflow.com/questions/5541312/how-to-pass-the-variable-from-included-template-to-the-template-where-it-is-incl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!