【问题标题】:Including a template does not render the variable value [duplicate]包含模板不会呈现变量值[重复]
【发布时间】:2011-07-29 13:39:03
【问题描述】:

可能重复:
how to pass the variable from included template to the template where it is included?

ma​​in.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="#.">
         {% 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

这个 html 被包含在 main.html

views.py

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

作为响应,它将发送part.html 但我正在使用foo_id 将它发送到main.htmlmain.html 包括part.html{{ foo_id }} 中的main.html 并没有给我任何价值。我用??? 表示了位置但是当我渲染整个模板时(不添加html div 中的数据)然后它给出正确的数据。

jquery

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

【问题讨论】:

  • 此处未回答问题的完全相同的副本:stackoverflow.com/questions/5541312/…
  • 抱歉,我需要更准确地表述问题
  • 您可以编辑您的问题以使其更清楚,而不是创建一个新帐户并重新发布问题。

标签: jquery python ajax django


【解决方案1】:

我不太明白你的问题。我假设您的意思是您希望 foo_id 可以从 AJAX 请求响应中访问,但这是不可能的,因为在发出 AJAX 请求之前呈现页面(和上下文集),所以 part.html 只是 django 的模板,它使用主模板的上下文来呈现整个页面。您需要根据响应在 JavaScript 中手动更改 foo_id,或者修复您的视图(从 ajax 视图和主视图调用相同的函数来获取 foo_id)

让我对你的问题感到困惑的是:

但是当我渲染整个模板(不在 div 中添加 html 数据)时,它会给出正确的数据。

,如果您不包含 part.html,我将其读作 foo_id 被设置,如果是这种情况,我很抱歉(即使它对我来说没有意义......)。

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 2019-04-04
    • 1970-01-01
    • 2016-02-23
    • 2019-04-09
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多