Working with Templates ====================== So far in the project you've created about six html templates for the different pages in the application. You've probably already noticed that there is a lot of redundancy in these html templates. In most applications there is often a lot of repetition, i.e. headers, navigation bars, side bars, footers, the scripts that are injected into each page, etc. To help you, Django provides template inheritance. It is pretty straightforward and is similar to inheritance in Python (and other languages). To use template inheritance you will need to do the following: * identity the parts of the html page that are repeated and common across your application * create a base html template which contains the commonalities along with the structure of your page - defined by blocks * for each page in your application that follows from the base html: * inherit from the base html template * insert the page specific html and template tags into the blocks For Rango, the commonalities between pages is the following html: ::
Rango
Base Template ------------- To tell Django that you want to specify what goes into the body section for each page you need to add in a *block* template tag. Create a new template called *base.html* and put in all the usual html pre-amble and declarations, as well as adding in the common functionality/layout that you would like to appear on each page. ::
Rango
{% block sidebar %}{% endblock %}
{% block content %}{% endblock %}
As in the previous examples using templates, the template tags are denoted by the *{% %}* parentheses with the tag inside. Here the blocks are called *sidebar*, *content* and *footer*. In templates which inherit from base.html, you will be able to specify what content you would like to be presented within those block. In a template you can define as many blocks as you need for your page layout. Inherited Template ------------------ Now you'll need to update all the other templates so that they all use *base.html*. This is done with the *extends* tag, so modify your *index.html* template as follows: :: {% extends 'base.html' %} {% block sidebar %}

Category List

{% endblock %} {% block content %}

Rango says: Hello World!


{% endblock %} Now, *index.html* inherits from *base.html* - and so any changes to *base.html* will propagate through to *index.html*, and any other template that inherits from *base.html*. Exercises --------- * Update the other templates so that they also inherit from base.html. For example, the *register.html* template would become: :: {% extends 'rango/base.html' %} {% block content %} {% if registered %}

Registered


Rango says: thank you for registering. {% else %}

Register here!


{% csrf_token %} {{ uform.as_p }} {{ pform.as_p }}
{% endif %} {% endblock %}