Chapter 5. Templates

In this chapter, we will discuss the following topics:

  • Features of Django's template language
  • Organizing templates
  • Bootstrap
  • Template inheritance tree pattern
  • Active link pattern

Understanding Django's template language features

It is time to talk about the third musketeer in the MTV trio—templates. Your team might have designers who take care of designing templates. Or you might be designing them yourself. Either way, you need to be very familiar with them. They are, after all, directly facing your users.

Let's start with a quick primer of Django's template language features.

Variables

Each template gets a set of context variables. Similar to Python's string format() method's single curly brace {variable} syntax, Django uses the double curly brace {{ variable }} syntax. Let's see how they compare:

  • In Pure Python the syntax is <h1>{title}</h1>. For example:
    >>> "<h1>{title}</h1>".format(title="SuperBook")
    '<h1>SuperBook</h1>'
    
  • The syntax equivalent in a Django template is <h1>{{ title }}</h1>.
  • Rendering with the same context will produce the same output as follows:
    >>> from django.template import Template, Context
    >>> Template("<h1>{{ title }}</h1>").render(Context({"title": "SuperBook"}))
    '<h1>SuperBook</h1>'
    

Attributes

Dot is a multipurpose operator in Django templates. There are three different kinds of operations—attribute lookup, dictionary lookup, or list-index lookup (in that order).

  • In Python, first, let's define the context variables and classes:
    >>> class DrOct:
            arms = 4
            def speak(self):
                return "You have a train to catch."
    >>> mydict = {"key":"value"}
    >>> mylist = [10, 20, 30]
    

    Let's take a look at Python's syntax for the three kinds of lookups:

    >>> "Dr. Oct has {0} arms and says: {1}".format(DrOct().arms, DrOct().speak())
    'Dr. Oct has 4 arms and says: You have a train to catch.'
    >>> mydict["key"]
     'value'
    >>> mylist[1]
     20
    
  • In Django's template equivalent, it is as follows:
    Dr. Oct has {{ s.arms }} arms and says: {{ s.speak }}
    {{ mydict.key }}
    {{ mylist.1 }}
    

Note

Notice how speak, a method that takes no arguments except self, is treated like an attribute here.

Filters

Sometimes, variables need to be modified. Essentially, you would like to call functions on these variables. Instead of chaining function calls, such as var.method1().method2(arg), Django uses the pipe syntax {{ var|method1|method2:"arg" }}, which is similar to Unix filters. However, this syntax only works for built-in or custom-defined filters.

Another limitation is that filters cannot access the template context. It only works with the data passed into it and its arguments. Hence, it is primarily used to alter the variables in the template context.

  • Run the following command in Python:
    >>> title="SuperBook"
    >>> title.upper()[:5]
     'SUPER'
    
  • Its Django template equivalent:
    {{ title|upper|slice:':5' }}"
    

Tags

Programming languages can do more than just display variables. Django's template language has many familiar syntactic forms, such as if and for. They should be written in the tag syntax such as {% if %}. Several template-specific forms, such as include and block are also written in the tag syntax.

  • Run the following command in Python:
    >>> if 1==1:
    ...     print(" Date is {0} ".format(time.strftime("%d-%m-%Y")))
     Date is 31-08-2014
    
  • Its corresponding Django template form:
    {% if 1 == 1 %} Date is {% now 'd-m-Y' %} {% endif %}
    

Philosophy – don't invent a programming language

A common question among beginners is how to perform numeric computations such as finding percentages in templates. As a design philosophy, the template system does not intentionally allow the following:

  • Assignment to variables
  • Advanced logic

This decision was made to prevent you from adding business logic in templates. From our experience with PHP or ASP-like languages, mixing logic with presentation can be a maintenance nightmare. However, you can write custom template tags (which will be covered shortly) to perform any computation, especially if it is presentation-related.

Tip

Best Practice

Keep business logic out of your templates.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.181.145