Search code examples
djangodjango-context

Django: Setting context by url's GET


How can you make a specific action based on the url by base.html?

I have two if -clauses as context statements in base.html. If there is algebra in the GET, then the given context should be shown.

My url.conf

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^algebra/$', 'algebra'),
    (r'^mathematics/$', 'mathematics'),

)

My base.html in pseudo-code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
  <body>
              {% if algebra %}                                    
                  <div>... -- do this -- </div> 
              {% endif %}

              {% if math %}
                  <div>... -- do this -- </div>
              {% endif %}

Solution

  • An alternative to Ned's variable-value-based method is to use two different templates that extend a common base template. E.g.

    In templates/base.html:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
    <html lang="en">
      <body>
          {% block main_body %}                                    
          {% endblock main_body %}                                    
           etc., etc.
    

    Then have your algebra view use templates/algebra.html:

    {% extends "base.html" %}
    
    {% block main_body %}
      do algebra stuff here
    {% end block main_body %}
    

    and do something similar for math or whatever. Each approach has advantages and disadvantages. Pick the one that feels like the best fit to your problem.

    Update: You pass "algebra.html" as the first argument to render_to_response(). It extends "base.html" in that it uses all of it except for the block(s) it explicitly replaces. See Template Inheritance for an explanation of how this works. Template inheritance is a very powerful concept for achieving a consistent look and feel across a large number of pages which differ in their body, but share some or all of the menus, etc. And you can do multi-level template inheritance which is extremely nice for managing sites that have subsections which have significant differences with the "main look" and yet want to share as much HTML/CSS as possible.

    This is a key principle in DRY (Don't Repeat Yourself) in the template world.