【问题标题】:how to pass the variable from included template to the template where it is included?如何将变量从包含的模板传递到包含它的模板?
【发布时间】:2011-07-29 07:38:19
【问题描述】:

在 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 变量值用于包含它的模板。

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    如果你只是渲染 foo:

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

    那么 'foo' 和包含的 'bar' 都具有相同的 'edit' 值。

    我不完全理解你的问题,但我回答了吗?

    【讨论】:

      【解决方案2】:

      使用您其他帖子中的详细信息,您应该对其进行编辑以包含在此帖子中:

      据我所知,您正在尝试将“选定”类添加到侧边栏菜单中。这对您不起作用,因为正如 gcbirzan 所说,您无法将 ajax 响应的上下文获取到基本模板中。最重要的是,您不会重新渲染基本模板,因此无论如何它都不会改变。

      使用 javascript,您可以从 part.html 中提取 foo_id。由于没有显示该代码,假设您的 foo_id 位于隐藏的 div 中,&lt;div id="foo_id" style="display:none;"&gt;foo_2&lt;/div&gt;

      现在你可以把你的 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');
          }
      
      });
      

      【讨论】:

        猜你喜欢
        • 2013-04-05
        • 2010-12-17
        • 2020-01-06
        • 2017-12-13
        • 2011-05-30
        • 1970-01-01
        • 2015-11-18
        • 1970-01-01
        • 2018-09-11
        相关资源
        最近更新 更多