tags:

views:

59

answers:

2

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 %}
+2  A: 

You don't show your view functions, but here's a simple structure:

def algebra(request):
    return common_view(request, algebra=True)

def math(request):
    return common_view(request, math=True)

def common_view(request, math=False, algebra=False):
    ctx = Context()
    ctx['algebra'] = algebra
    ctx['math'] = math
    # blah blah, all the other stuff you need in the view...
    return render_to_response("base.html", ctx)

(I might have some typos, it's off the top of my head).

Ned Batchelder
+1  A: 

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.

Peter Rowell
What is your view -method? Is it `def common_view(request): ctx = Context(); return_to_response("base.html", ctx)` ?
Masi