Take the 2-minute tour ×

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

<html lang="en">
              {% if algebra %}                                    
                  <div>... -- do this -- </div> 
              {% endif %}

              {% if math %}
              {% endif %}
share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

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:

<html lang="en">
      {% 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.

share|improve this answer
What is your view -method? Is it def common_view(request): ctx = Context(); return_to_response("base.html", ctx) ? –  Masi Jan 5 '10 at 4:04
add comment

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).

share|improve this answer
add comment

Your Answer

