Alex Rivera | Logout

Python / Django - If statement in template around extends

Asked 2011-02-18T15:27:18.347
26

I would like to have a template that extends another conditionally. Basically, when a variable called "ajax" is true I DO NOT want to have the template extend another.

{% if not ajax %}
    {% extends "/base.html" %}
{% endif %}

Any clues?

Edit
Report

1 Answer

6

I was looking for the solution of the same problem and came with a bit better workaround than suggested by Klaus Byskov Hoffmann. It is better because you don't have to have 2 separate base templates for ajax and non-ajax requests and, which is more important, you don't have to define if statement that will define which base template to use in EACH controller.

In your case the solution would be:

page.html

{% extends "/base.html" %}
{% block body %}
    hello world
{% endblock body %}

base.html

{% if not ajax %}
<html>
    <head></head>
    <body>
        LOGO and other stuff...

{% endif %}{% block body %}{% endblock body %}{% if not ajax %}

        FOOTER
    </body>
</html>
{% endif %}

So, base.html is always included but it prints its content only when not ajax.

UPDATE: This can be simplified by creating and adding a new ConextProcessor that will populate ajax context variable from the HttpRequest.is_ajax(), so you don't have to do anything extra in your controllers and templates at all.

answered 2011-07-22T10:50:35.737

Your Answer