如何将变量从包含的模板传递到包含的模板? [英] how to pass the variable from included template to the template where it is included?

查看:152
本文介绍了如何将变量从包含的模板传递到包含的模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django视图中: -

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)

有两个模板:
主模板(foo-templates.html)其中包含模板(bar-templates.html)。在上下文编辑用户被传递到 bar-templates.html 但此变量也用于 foo-templates.html 。在django中,我们习惯了 {{编辑}} 来捕获变量。由于此变量位于 bar-templates.html 中。如何使用这个 foo-templates.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.

推荐答案

从您的其他帖子中使用您应编辑的详细信息,以便包含在此文章中:

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

从我可以看出,您尝试添加selected 上课到你的边栏菜单。这对你来说不行,因为gcbirzan说,你不能将你的ajax响应的上下文放在你的基本模板中。除此之外,您不会重新渲染基本模板,因此它不会改变。

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.

使用javascript可以从您的 part.html 。由于该代码未显示,我们假设您的foo_id位于隐藏的div中,< div id =foo_idstyle =display:none;> foo_2< / div> code>

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>

现在您可以将ajax函数更改为如下:

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

});

这篇关于如何将变量从包含的模板传递到包含的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆