【问题标题】:Nested {% block %} statement runs independent of {% if-statement %} validity Django嵌套 {% block %} 语句运行独立于 {% if-statement %} 有效性 Django
【发布时间】:2013-03-04 06:18:15
【问题描述】:

Django v1.4.3下

为什么下面 Django 模板案例 1 中的 if 语句总是显示块语句的内容,而与 if 语句是否为 TRUE 无关?

是否总是在模板中的 if 语句之前执行块语句? (也许我在文档中错过了这一点。)

View.py(请注意,故意“不”提供 map_url 用于测试目的):

def post_address(request):
    return render_to_response(
        'record/post_address.html',
        {'form': form},
        context_instance=RequestContext(request)
    )

base_integrated_form.html 父模板包含

{% block after_form %}
{% endblock after_form %}

post_address.html(两种情况) Django 模板案例一:(在 if 语句中嵌套 block-statement 会导致 block-statement 的内容始终显示在浏览器中,与是否提供 map_url 无关。)

{% extends "base_integrated_form.html" %}
{% if map_url %}
   {% block after_form %}
   <div style="max-width:555px; height:240px; margin-left:auto; margin-right:auto;">
        <iframe id="map" width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="{{ map_url }}" style="border: 0px solid black"></iframe>
    </div>
    {% endblock after_form %}
{% endif %}

Django 模板案例2(如果提供map_url,则在block-statement中嵌套if-statement只会在浏览器中显示block-statement的内容。):

{% extends "base_integrated_form.html" %}
{% block after_form %}
{% if map_url %}
   <div style="max-width:555px; height:240px; margin-left:auto; margin-right:auto;">
        <iframe id="map" width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="{{ map_url }}" style="border: 0px solid black"></iframe>
    </div>
{% endif %}
{% endblock after_form %}

【问题讨论】:

    标签: django django-templates django-views


    【解决方案1】:

    块标签不同于其他模板标签,它们是模板继承系统的核心部分。

    本质上,块标签在模板最初加载时(渲染之前)被评估,以便 Django 可以查找继承链并构建最终的模板对象。这意味着其他标签内的块(如'if')将无法按您预期的方式工作,因为一旦真正的模板渲染开始,块标签就不再存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 2012-06-01
      相关资源
      最近更新 更多