嵌套{%block%}语句独立于{%if-statement%}有效性Django

嵌套{%block%}语句独立于{%if-statement%}有效性Django

问题描述:

在Django v1.4.3下

Under Django v1.4.3

为什么Django Template Case 1中的if语句总是显示block语句的内容,而不管if-语句为TRUE?

Why does the if-statement in Django Template Case 1 below always display the contents of the block-statement independent of whether the if-statement is TRUE?

是否在模板中的if-statements之前总是执行block-statements? (可能我在文档中错过了)。

Are block-statements always executed before if-statements in templates? (Maybe I missed this in the documentation.)

View.py(请注意,map_url有意不用于测试目的):

View.py (note that map_url is intentionally 'not' provided for testing purposes):

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

base_integrated_form。 html父模板包含

base_integrated_form.html Parent template contains

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

post_address.html(两个案例)
Django模板案例1:(在if语句中嵌套块语句将导致block-statement的内容始终显示在浏览器中,无论是否提供 map_url 。)

post_address.html (Two Cases) Django Template Case 1: (Nesting the block-statement in the if-statement will cause the contents of the block-statement to always display in the browser independent of whether map_url is provided or NOT.)

{% 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(在块语句中嵌套if语句如果提供了 map_url ,则仅在浏览器中显示块语句的内容。):

Django Template Case 2 (Nesting the if-statement in the block-statement only displays the contents of the block-statement in the browser if map_url is provided.):

{% 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 %}


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

Block tags are different to other template tags, they're a core part of the template inheritance system.

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

Essentially, block tags are evaluated when the template is initially loaded (before rendering), so that Django can look up the inheritance chain and build the final template object. This means that blocks inside other tags (like 'if') won't work the way you expect, because the block tags don't exist anymore once the real template rendering begins.