Nested {% block %} statement runs independent of {% if-statement %} validity Django

♀尐吖头ヾ 提交于 2019-12-13 04:27:19

问题


Under Django v1.4.3

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?

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

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 Parent template contains

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

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

回答1:


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

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.



来源:https://stackoverflow.com/questions/15434017/nested-block-statement-runs-independent-of-if-statement-validity-dja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!