Previous Page Next Page

Hour 8. Using Built-in Template Tags to Enhance Views

What You'll Learn in This Hour

  • How to use for loops to generate HTML code from lists

  • How to use if logic to add conditional HTML code to templates

  • How to add dynamic links to templates

  • How to reduce template code by using the with tag

  • How to add cycling behavior to enhance table views

Django has several tags that allow you to implement some basic logic in your templates that helps you reduce the amount of HTML code that you need to write. This hour covers using Django's built-in template tags to create more complex and useful templates.

Implementing Loops

One of the most common tags that you will use will be the for tag to implement for loops inside your HTML documents. The for tag allows you to navigate through a list of strings or objects and generate HTML code for each item in the list.

For example, if you have a list of several URLs for which you want to write HTML links in a template, you could implement a for tag similar to the following code snippet, where links is a list object:

{% for lnk in links %}
    <li><a href="{{ lnk }}"> {{ lnk }}</a></li>
{% endfor %}

Using this code in your template renders the list of links in the HTTP response. It doesn't matter how many links you need to put in the list. You do not need to add code to your HTML template to do so.

By the Way

You can add as many lines of code inside the for tag section as are needed and then add the {% endfor %} tag to close the section.


The for tag can also handle dictionary objects. Use the following syntax:

{% for key, value in dict %}

For example, if you have a dictionary containing people's names as the key and phone numbers as the value, you could use the following code snippet in a template to render the list of names and phone numbers:

{% for name, phone in phoneList %}
    <h2>Name:  {{ name }} </h2>
    <li>Phone:  {{ phone }} </li>
{% endfor %}

Did you Know?

You can access the items in a list in reverse order by using the reversed tag in a for tag statement. For example, the following code displays the entries in the books list in reverse order:

{% for title in books reversed %}


Django also allows you to use for loops to process lists of lists as long as you can unpack the values in each sublist into a set of names. For example, if you have a list of GPS coordinates that are formatted as a [location, lat, long] list, you could use the following code snippet in a template to render the list of GPS locations:

{% for location, lat, long in gpsList %}
    <h2>Location:  {{ location }} </h2>
    <li>Coordinates:  {{ lat }}:{{ long }}</li>
{% endfor %}

Django provides the forloop variable in loop operations. It can provide you with information such as counters and parent loops. Table 8.1 lists the available fields in the forloop variable object.

Table 8.1. Fields Available in the forloop Variable
VariableDescription
forloop.counterThe loop's current iteration (1-based index)
forloop.counter0The loop's current iteration (0-based index)
forloop.revcounterThe number of iterations from the end of the loop (1-based index)
forloop.revcounter0The number of iterations from the end of the loop (0-based index)
forloop.firstIs true if this is the first iteration through the loop
forloop.lastIs true if this is the last iteration through the loop
forloop.parentloopAccesses the forloop object in the loop before the current one (used when nesting loops)


Try It Yourself: Use a for Loop to Render a List of Objects

In this example, you will create a template that renders a list of Person objects for the index() function of the People application view.

Follow these steps to create an HTML document to display Person details and turn it into a Django template:

1.
Using a text editor, create a file called iFriends/templates/People/person_index.html.

2.
Add the following line of code to person_index.html to extend the iFriends_base.html base template, as shown in Listing 8.1:

{% extends "iFriends_base.html" %}

3.
Add the following line of code to add a title block to be inserted into the iFriends_base.html template, as shown in Listing 8.1:

{% block title %}People{% endblock %}

4.
Add the following content block of code to generate a table that will contain the list of people, as shown in Listing 8.1:

{% block content %}
<table width=100%>
<tr bgcolor="aabbcc"><td colspan="3">
<font size="5" color="white">Personal List</font>
</td></tr>
<tr valign="top"><td width=30% bgcolor="aaaaaa"><font color="white" size="5">
</font>
   </td></tr>
{% endblock %}


					  

5.
Add the following for loop to navigate through the list of people and generate a numbered list of people in the view, as shown in Listing 8.1:

{% for p in pList %}
    <p>{{ forloop.counter }}. {{ p.name }}</p>
{% endfor %}

6.
Save the file.

7.
Open the iFriends/People/views.py file in an editor.

8.
Delete the current contents of the index() function.

9.
Add the following line of code to the index() function to generate a list of Person objects, as shown in Listing 8.2:

pList = Person.objects.all()

10.
Add the following line of code to the index() function to render the view using the person_index.html template and adding the list of people generated in step 9 to the dictionary, as shown in Listing 8.2:

return render_to_response('people/person_index.html', {'pList': pList})

11.
Save the views.py file.

12.
Access the following URL in a web browser to verify that the view is working correctly, as shown in Figure 8.1:

http://127.0.0.1:8000/People/

Figure 8.1. Web page generated by the index() view of the People application.


Listing 8.1. Full Contents of iFriends/templates/People/person_index.html

{% extends "iFriends_base.html" %}

{% block title %}People{% endblock %}
{% block content %}
<table width=100%>
<tr bgcolor="aabbcc"><td colspan="3">
<font size="5" color="white">Personal List</font>
</td></tr>
<tr valign="top"><td width=30% bgcolor="aaaaaa"><font color="white" size="5">
{% for p in pList %}
    <p>{{ forloop.counter }}. {{ p.name }}</p>
{% endfor %}
</font></td></tr>
{% endblock %}


					  

Listing 8.2. Full Contents of iFriends/People/views.py

from django.http import HttpResponse
from iFriends.People.models import Person
from django.shortcuts import render_to_response, get_object_or_404

def index(request):
    pList = Person.objects.all()
    return render_to_response('people/person_index.html', {'pList': pList})

def details(request, pID='0', opts=()):
    p = get_object_or_404(Person, pk=pID)
    return render_to_response('people/person_details.html', {'p': p})

By the Way

Did you notice how much the iFriends/People/views.py file has shrunk? One of the best things about Django is that it really reduces the amount of code needed to generate web pages.



Previous Page Next Page