Django Templates and App Engine Controllers

Django templates are HTML plus scripting code for the dynamic information that should appear in a page.

Template Values {}

The simplest way to specify dynamic content within an HTML template is with double curly brackets, as in the following example:

<p> The interest earned is: {{interest}} </p>

In this sample, the <p> and </p> are normal HTML tags for a paragraph. The text 'The interest after 30 years is' will appear just like with any HTML paragraph.

The double curly brackets are not HTML but scripting code. The term inside, interest, is a placeholder, sort of like the name and address in a form letter.

The string {{interest}} will be replaced when the HTML template is converted into straight HTML that is sent over the network to the user.

Server code is responsible for computing values and using them to replace the dynamic double-curly bracket template variables.

The server code that does this is called a controller. Here's an example of controller code:

class CalcController(webapp.RequestHandler):
  def get(self):
    principalString=self.request.get('principal')
    rateString = self.request.get('rate')
    principal = int(principalString)
    rate = int(rateString)
    interest = principal*rate/100
    interestString = str(interest)
   # set up the template_values with the list of people returned.
    template_values= {'interest':interestString, 'principal':principalString}
    # render the page using the template engine
    path = os.path.join(os.path.dirname(__file__),'index.html')
    self.response.out.write(template.render(path,template_values))


The code computes the value interest, then sticks it into a special variable called template_values. When the page is rendered, on the last line, the computed template_values replace the {{ }} variables in the HTML template. If the interest computed were $5000 for our sample, the HTML would read as:

The interest earned is 5000

Displaying Objects
The above sample demonstrated the simplest form of dynamic value being inserted into a template: a string value. An HTML template can also display more complex information, including data within an object. For example, if a controller sends the template a person object:

    # some code to get a person object would go above
    template_values= {'person': person}
    
# render the page using the template engine
    path = os.path.join(os.path.dirname(__file__),'index.html')
    self.response.out.write(template.render(path,template_values))

 the template can display the fields of a person, e.g.,

    <p> {{person.firstName}} &nbsp {{person.lastName}} </p>

This code would work as long as person is an instance of some class (e.g. Person) that has the fields firstName and lastName, e.g.,

    
class Person(db.Model)
        firstName=db.StringProperty()
        lastName=db.StringProperty()

Displaying Dynamic Lists

Template can also display information that is embedded in a list of objects. The controller sends the list in the template_values, as in the following sample:

    name = self.request.get("lastName")
    matching_people = db.GqlQuery("Select * from Person where lastName=:1",name)
    template_values= {'people': matching_people}
    
# render the page using the template engine
    path = os.path.join(os.path.dirname(__file__),'index.html')
    self.response.out.write(template.render(path,template_values))

The code above gets the last name sent in as a parameter to the request, looks up the people whose last name matches, and sticks the resulting list in the template_values.

The HTML template would use a for loop to display the list. For the above example, we're displaying a list of Person objects named people, so we have:

    <ul>
    {% for p in people %}
    <li>    {{p.firstName}} &nbsp {{p.lastName}} </li>
    {% endfor %}
    </ul>
   
With Django templates, code such as for loops and if statements are specified within {%      %}. In this case, we are using a for loop but there are other programming constructs as well (see the Django Template guide).

The ul and li tags are standard HTML for displaying a list of information.

Note that the variable p in the HTML code is not something sent in the template_values: it is a placeholder for the loop-- it is the person item for each iteration.

Now consider a slightly more complicated example, such as with a social network. Suppose that our person objects have a property which is a list of the person's friends. Then we might  have the controller just send us a person object, and we can use it to list the friends:

    <ul>

    {% for friend in person.friends %}

    <li>    {{p.firstName}} &nbsp {{p.lastName}} </li>
    
{% endfor %}
    </ul>


Note for this to work, friends has to be a property of the class Person. If friends is a function of Person, you can use the @property specification to make it a property:

class Person(db.Model)
    firstName=db.StringProperty()
    lastName=db.StringProperty()
   
    @property
    def friends():
                # code to get the person's friends

The @property specification is necessary because the template code cannot call a function directly.

Recent site activity