簡體   English   中英

如何將變量從包含的模板傳遞到包含它的模板?

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

在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

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}} //這里它給我編輯值這是我從視圖發送的模板。

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

使用您另一篇文章中的詳細信息,您應對其進行編輯以包括在此內容中:

據我所知,您正在嘗試在側邊欄菜單中添加“選定”類。 這對您不起作用,因為正如gcbirzan所說,您將無法將ajax響應的上下文包含到基本模板中。 最重要的是,您不會重新渲染基本模板,因此無論如何都不會更改。

您可以使用javascript從part.html提取part.html 由於未顯示該代碼,因此可以假設您將foo_id放在一個隱藏的div中, <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');
    }

});

如果僅渲染foo:

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

那么“ foo”和包含的“ bar”的“ edit”值都相同。

我不完全理解您的問題,但是我已經回答了嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM