Templates in Django

Django makes it possible to separate python and HTML, the python goes in views and HTML goes in templates. To link the two, Django relies on the render function and the Django Template language.

The Render Function

This function takes three parameters −

  • Request − The initial request.
  • The path to the template − This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables.
  • Dictionary of parameters − A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view.

Django Template Language (DTL)

Django’s template engine offers a mini-language to define the user-facing layer of the application.

Displaying Variables

A variable looks like this: {{variable}}. The template replaces the variable by the variable sent by the view in the third parameter of the render function. Let's change our hello.html to display today’s date −

hello.html

<html>
   
   <body>
      Hello World!!!<p>Today is {{today}}</p>
   </body>
   
</html>

Then our view will change to −

def hello(request):
   today = datetime.datetime.now().date()
   return render(request, "hello.html", {"today" : today})

We will now get the following output after accessing the URL/myapp/hello −

Hello World!!!
Today is Sept. 11, 2015

As you have probably noticed, if the variable is not a string, Django will use the __str__ method to display it; and with the same principle you can access an object attribute just like you do it in Python. For example: if we wanted to display the date year, my variable would be: {{today.year}}.

Filters

They help you modify variables at display time. Filters structure looks like the following: {{var|filters}}.

Some examples −

  • {{string|truncatewords:80}} − This filter will truncate the string, so you will see only the first 80 words.
  • {{string|lower}} − Converts the string to lowercase.
  • {{string|escape|linebreaks}} − Escapes string contents, then converts line breaks to tags.

You can also set the default for a variable.

Tags

Tags lets you perform the following operations: if condition, for loop, template inheritance and more.

Tag if

Just like in Python you can use if, else and elif in your template −

<html>
   <body>
   
      Hello World!!!<p>Today is {{today}}</p>
      We are
      {% if today.day == 1 %}
      
      the first day of month.
      {% elif today.day == 30 %}
      
      the last day of month.
      {% else %}
      
      I don't know.
      {%endif%}
      
   </body>
</html>

In this new template, depending on the date of the day, the template will render a certain value.

Tag for

Just like 'if', we have the 'for' tag, that works exactly like in Python. Let's change our hello view to transmit a list to our template −

def hello(request):
   today = datetime.datetime.now().date()
   
   daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek})

The template to display that list using {{ for }} −

<html>
   <body>
      
      Hello World!!!<p>Today is {{today}}</p>
      We are
      {% if today.day == 1 %}
      
      the first day of month.
      {% elif today.day == 30 %}
      
      the last day of month.
      {% else %}
      
      I don't know.
      {%endif%}
      
      <p>
         {% for day in days_of_week %}
         {{day}}
      </p>
		
      {% endfor %}
      
   </body>
</html>

And we should get something like −

Hello World!!!
Today is Sept. 11, 2015
We are I don't know.
Mon
Tue
Wed
Thu
Fri
Sat
Sun

Block and Extend Tags

A template system cannot be complete without template inheritance. Meaning when you are designing your templates, you should have a main template with holes that the child's template will fill according to his own need, like a page might need a special css for the selected tab.

Let’s change the hello.html template to inherit from a main_template.html.

main_template.html

<html>
   <head>
      
      <title>
         {% block title %}Page Title{% endblock %}
      </title>
      
   </head>
	
   <body>
   
      {% block content %}
         Body content
      {% endblock %}
      
   </body>
</html>

hello.html

{% extends "main_template.html" %}
{% block title %}My Hello Page{% endblock %}
{% block content %}

Hello World!!!<p>Today is {{today}}</p>
We are
{% if today.day == 1 %}

the first day of month.
{% elif today.day == 30 %}

the last day of month.
{% else %}

I don't know.
{%endif%}

<p>
   {% for day in days_of_week %}
   {{day}}
</p>

{% endfor %}
{% endblock %}

In the above example, on calling /myapp/hello we will still get the same result as before but now we rely on extends and block to refactor our code −

In the main_template.html we define blocks using the tag block. The title block will contain the page title and the content block will have the page main content. In home.html we use extends to inherit from the main_template.html then we fill the block define above (content and title).

Comment Tag

The comment tag helps to define comments into templates, not HTML comments, they won’t appear in HTML page. It can be useful for documentation or just commenting a line of code.

 

 

 

#######################################################

Tags

if/else

The {% if %} tag evaluates a variable, and if that variable is “True” (i.e., it exists, is not empty, and is not a false Boolean value), the system will display everything between {% if %} and {% endif %}, for example:

{% if today_is_weekend %}
    <p>Welcome to the weekend!</p>
{% endif %}

An {% else %} tag is optional:

{% if today_is_weekend %}
    <p>Welcome to the weekend!</p>
{% else %}
    <p>Get back to work.</p>
{% endif %}

Make sure to close each {% if %} with an {% endif %}, otherwise Django will throw a TemplateSyntaxError.

The if tag may also take one or several {% elif %} clauses as well:

{% if athlete_list %}
    <p>Number of athletes: {{ athlete_list|length }}</p>
{% elif athlete_in_locker_room_list %}
    <p>Athletes should be out of the locker room soon!</p>
{% elif ...
...
{% else %}
    <p>No athletes.</p>
{% endif %}

The {% if %} tag accepts andor, or not for testing multiple variables, or to negate a given variable. For example:

{% if athlete_list and coach_list %}
    <p>Both athletes and coaches are available.</p>
{% endif %}

{% if not athlete_list %}
    <p>There are no athletes.</p>
{% endif %}

{% if athlete_list or coach_list %}
    <p>There are some athletes or some coaches.</p>
{% endif %}

{% if not athlete_list or coach_list %}
    <p>There are no athletes or there are some coaches.</p>
{% endif %}

{% if athlete_list and not coach_list %}
    <p>There are some athletes and absolutely no coaches.</p>
{% endif %}

Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or  e.g.:

{% if athlete_list and coach_list or cheerleader_list %}

will be interpreted like:

if (athlete_list and coach_list) or cheerleader_list

Multiple uses of the same logical operator are fine, but you can’t combine different operators. For example, this is valid:

{% if athlete_list or coach_list or parent_list or teacher_list %}

The {% if %} also accepts in / not in for testing whether a given value is or isn’t in the specified container, and is / is not for testing if two entities are the same object.

For example:

{% if "bc" in "abcdef" %}
    This appears since "bc" is a substring of "abcdef"
{% endif %}

{% if user not in users %}
    If users is a list, this will appear if user isn't an element of the list.
{% endif %}

{% if somevar is True %}
    This appears if and only if somevar is True.
{% endif %}

{% if somevar is not None %}
    This appears if somevar isn't None.
{% endif %}

for

The {% for %} tag allows you to loop over each item in a sequence. As in Python’s forstatement, the syntax is for X in Y, where Y is the sequence to loop over and X is the name of the variable to use for a particular cycle of the loop. Each time through the loop, the template system will render everything between {% for %} and {% endfor %}. For example, you could use the following to display a list of athletes given a variable athlete_list:

<ul>
    {% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
    {% endfor %}
</ul>

Add reversed to the tag to loop over the list in reverse:

{% for athlete in athlete_list reversed %}
...
{% endfor %}

It’s possible to nest {% for %} tags:

{% for athlete in athlete_list %}
<h1>{{ athlete.name }}</h1>
<ul>
    {% for sport in athlete.sports_played %}
    <li>{{ sport }}</li>
    {% endfor %}
</ul>
{% endfor %}

If you need to loop over a list of lists, you can unpack the values in each sub list into individual variables.

For example, if your context contains a list of (x,y) coordinates called points, you could use the following to output the list of points:

{% for x, y in points %}
    <p>There is a point at {{ x }},{{ y }}</p>
{% endfor %}

This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

A common pattern is to check the size of the list before looping over it, and outputting some special text if the list is empty:

{% if athlete_list %}
    {% for athlete in athlete_list %}
        <p>{{ athlete.name }}</p>
    {% endfor %}
{% else %}
    <p>There are no athletes. Only computer programmers.</p>
{% endif %}

Because this pattern is so common, the for tag supports an optional {% empty %}clause that lets you define what to output if the list is empty. This example is equivalent to the previous one:

{% for athlete in athlete_list %}
    <p>{{ athlete.name }}</p>
{% empty %}
    <p>There are no athletes. Only computer programmers.</p>
{% endfor %}

There is no support for “breaking out” of a loop before the loop is finished. If you want to accomplish this, change the variable you’re looping over so that it includes only the values you want to loop over.

Similarly, there is no support for a “continue” statement that would instruct the loop processor to return immediately to the front of the loop. (See the section “Philosophies and Limitations” later in this chapter for the reasoning behind this design decision.)

Within each {% for %} loop, you get access to a template variable called forloop. This variable has a few attributes that give you information about the progress of the loop:

  • forloop.counter is always set to an integer representing the number of times the loop has been entered. This is one-indexed, so the first time through the loop, forloop.counter will be set to 1. Here’s an example:
    {% for item in todo_list %}
        <p>{{ forloop.counter }}: {{ item }}</p>
    {%endfor %}
  • forloop.counter0 is like forloop.counter, except it’s zero-indexed. Its value will be set to 0 the first time through the loop.
  • forloop.revcounter is always set to an integer representing the number of remaining items in the loop. The first time through the loop, forloop.revcounterwill be set to the total number of items in the sequence you’re traversing. The last time through the loop, forloop.revcounter will be set to 1.
  • forloop.revcounter0 is like forloop.revcounter, except it’s zero-indexed. The first time through the loop, forloop.revcounter0 will be set to the number of elements in the sequence minus 1. The last time through the loop, it will be set to 0.
  • forloop.first is a Boolean value set to True if this is the first time through the loop. This is convenient for special-casing:
    {% for object in objects %}
        {% if forloop.first %}
            <li class="first">
        {% else %}
            <li>
        {% endif %}
        {{ object }}</li>
    {% endfor %}
  • forloop.last is a Boolean value set to True if this is the last time through the loop. A common use for this is to put pipe characters between a list of links:
    {% for link in links %}
        {{ link }}{% if not forloop.last %} | {% endif %}
    {% endfor %}

    The above template code might output something like this:

      Link1 | Link2 | Link3 | Link4

    Another common use for this is to put a comma between words in a list:

    <p>Favorite places:</p>
    {% for p in places %}
        {{ p }}{% if not forloop.last %}, {% endif %}
    {% endfor %}
  • forloop.parentloop is a reference to the forloop object for the parent loop, in case of nested loops. Here’s an example:
      {% for country in countries %}
      <table>
          {% for city in country.city_list %}
          <tr>
              <td>Country #{{ forloop.parentloop.counter }}</td>
              <td>City #{{ forloop.counter }}</td>
              <td>{{ city }}</td>
          </tr>
          {% endfor %}
      </table>
      {% endfor %}

The forloop variable is only available within loops. After the template parser has reached {% endfor %}forloop disappears.

ifequal/ifnotequal

Comments

Just as in HTML or Python, the Django template language allows for comments. To designate a comment, use {# #}:

{# This is a comment #}

The comment will not be output when the template is rendered. Comments using this syntax cannot span multiple lines. This limitation improves template parsing performance.

In the following template, the rendered output will look exactly the same as the template (i.e., the comment tag will not be parsed as a comment):

This is a {# this is not
a comment #}
test.

If you want to use multi-line comments, use the {% comment %} template tag, like this:

{% comment %}
This is a
multi-line comment.
{% endcomment %}

The comment tag may contain an optional note (e.g. to explain why that section of code has been commented out):

{% comment "This is the optional note" %}
    ...
{% endcomment %}

Comment tags cannot be nested.

Filters

As explained earlier in this chapter, template filters are simple ways of altering the value of variables before they’re displayed. Filters use a pipe character, like this:

{{ name|lower }}

This displays the value of the {{ name }} variable after being filtered through the lowerfilter, which converts text to lowercase. Filters can be chained – that is, they can be used in tandem such that the output of one filter is applied to the next.

Here’s an example that takes the first element in a list and converts it to uppercase:

{{ my_list|first|upper }}

Some filters take arguments. A filter argument comes after a colon and is always in double quotes. For example:

{{ bio|truncatewords:"30" }}

This displays the first 30 words of the bio variable.

The following are a few of the most important filters. Appendix E covers the rest.

  • addslashes: Adds a backslash before any backslash, single quote, or double quote. This is useful for escaping strings. For example:{{ value|addslashes }}.
  • date: Formats a date or datetime object according to a format string given in the parameter. For example: {{ pub_date|date:"F j, Y" }}Format strings are defined in Appendix E.
  • length: Returns the length of the value. For a list, this returns the number of elements. For a string, this returns the number of characters. If the variable is undefined, length returns 0.

Philosophies and Limitations

Now that you’ve gotten a feel for the Django Template Language (DTL), it’s probably time to explain the basic design philosophy behind the DTL.

First and foremost, the limitations to the DTL are intentional.

Django was developed in the high volume, ever-changing environment of an online newsroom. The original creators of Django had a very definite set of philosophies in creating the DTL.

These philosophies remain core to Django today. They are:

  1. Separate logic from presentation
  2. Discourage redundancy
  3. Be decoupled from HTML
  4. XML is bad
  5. Assume designer competence
  6. Treat whitespace obviously
  7. Don’t invent a programming language
  8. Ensure safety and security
  9. Extensible

1. Separate logic from presentation

A template system is a tool that controls presentation and presentation-related logic – and that’s it. The template system shouldn’t support functionality that goes beyond this basic goal.

2. Discourage redundancy

The majority of dynamic web sites use some sort of common site-wide design – a common header, footer, navigation bar, etc. The Django template system should make it easy to store those elements in a single place, eliminating duplicate code. This is the philosophy behind template inheritance.

3. Be decoupled from HTML

The template system shouldn’t be designed so that it only outputs HTML. It should be equally good at generating other text-based formats, or just plain text.

4. XML should not be used for template languages

Using an XML engine to parse templates introduces a whole new world of human error in editing templates – and incurs an unacceptable level of overhead in template processing.

5. Assume designer competence

The template system shouldn’t be designed so that templates necessarily are displayed nicely in WYSIWYG editors such as Dreamweaver. That is too severe of a limitation and wouldn’t allow the syntax to be as nice as it is.

Django expects template authors are comfortable editing HTML directly.

6. Treat whitespace obviously

The template system shouldn’t do magic things with whitespace. If a template includes whitespace, the system should treat the whitespace as it treats text – just display it. Any whitespace that’s not in a template tag should be displayed.

7. Don’t invent a programming language

The template system intentionally doesn’t allow the following:

  • Assignment to variables
  • Advanced logic

The goal is not to invent a programming language. The goal is to offer just enough programming-esque functionality, such as branching and looping, that is essential for making presentation-related decisions.

The Django template system recognizes that templates are most often written by designers, not programmers, and therefore should not assume Python knowledge.

8. Safety and security

The template system, out of the box, should forbid the inclusion of malicious code – such as commands that delete database records. This is another reason why the template system doesn’t allow arbitrary execution of Python code.

9. Extensibility

The template system should recognize that advanced template authors may want to extend its technology. This is the philosophy behind custom template tags and filters.

DTL Philosophy – Concluding Thoughts

Having worked with many different templating systems myself over the years, I whole-heartedly endorse this approach – the DTL and the way it has been designed is one of the major pluses of the Django framework.

When the pressure is on to Get Stuff Done, and you have both designers and programmers trying to communicate and get all the of the last minute tasks done, Django just gets out of the way and lets each team concentrate on what they are good at.

Once you have found this out for yourself through real-life practice, you will find out very quickly why Django really is the “framework for perfectionists with deadlines”.

More than any other component of web applications, template syntax is highly subjective, and programmers’ opinions vary wildly. The fact that Python alone has dozens, if not hundreds, of open source template-language implementations supports this point. Each was likely created because its developer deemed all existing template languages inadequate.

With all this in mind, Django is flexible – it does not require you to use the DTL. All of the most recent versions of Django, including Django 1.11, ship with the popular Jinja2template engine as well as the DTL to provide developers with options.

Because Django is intended to be a full-stack web framework that provides all the pieces necessary for web developers to be productive, most times it’s more convenient to use the DTL, but it’s not a strict requirement in any sense.

 

##################################

mywebsite/myapp/hello2.html

<html>

<body>
Hello World!!!<p>n is {{n}}</p>
If is not working with >
{% if n == 70 %}

GRADE A
{% elif n > 60 %}

GRADE B
{% else %}

FAILED
{%endif%}

# For loop is working fine with dictionary
<p>
{% for day in days %}
{{day}}
</p>

{% endfor %}
</body>

</html>

mywebsite/myapp/views.py

def hello3(request,id):
return render(request, "hello2.html", {"n" : id, "days":["mon","tue","wed"]})

mywebiste/myapp/views.py

re_path('temp(\d+)', views.hello3,name='id'),