Django template
Tags: python, beginners, django, webdev
Published: 2020-03-02 21:37:36

This is a continuation of the Python <a href="https://www.djangoproject.com/">Django</a> web app article. 

In the <a href="https://dev.to/toebes618/django-create-first-project-3e7b">previous article</a>, we used `django.http.httpResponse()` to output the word "Hello World!". This way of mixing data with views is not in line with Django's MVC thinking.

If you want, you can put your <a href="https://www.pythonanywhere.com/?affiliate_id=00535ced">Python app online</a>

## Templates

In the project in our previous article, we create the templates directory under the HelloWorld directory and create the hello.html file, the entire directory structure is as follows:

```
HelloWorld/
|-- HelloWorld
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- settings.py
|   |-- settings.pyc
|   |-- urls.py
|   |-- urls.pyc
|   |-- view.py
|   |-- view.pyc
|   |-- wsgi.py
|   `-- wsgi.pyc
|-- manage.py
`-- templates
    `-- hello.html
```

Hello.html The file code is as follows:

```html
<h1>{{ hello }}</h1>
```

We know from the template that the variable uses double parentheses.

Next we need to explain the path to the template file to Django, modify HelloWorld/sets.py, modify the DIRS in TEMPLATES to be BASE_DIR /templates, as follows:

```python
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR+"/templates",],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
```

We now modify the view.py to add a new object to submit data to the template:

```python
#-*- coding: utf-8 -*-

#from django.http import HttpResponse
from django.shortcuts import render

def hello(request):
    context = {}
    context['hello'] = 'Hello World!'
    return render(request, 'hello.html', context)
```

As you can see, here we replaced the httpResponse we used. The render also uses a dictionary context as an argument.

The key value of the element in the context dictionary, "hello", corresponds to the variable in the template.

Visit again at /hello/ to see the page:

![django template](https://dev-to-uploads.s3.amazonaws.com/i/usy99dxg80bcxw28t0k0.jpg)

This allows us to use templates to output data, so that the data can be separated from the view.

Next, we'll take a look at the syntax rules that are commonly used in the template.

## Django template language

### if/else label

Like in the Python programming language, tempates allow for use of <a href="https://pythonbasics.org/if-statements/">if statements</a>. The basic syntax format is as follows:

```python
{% if condition %}
     ... display
{% endif %}
```
Or:
```python
{% if condition1 %}
   ... display 1
{% elif condiiton2 %}
   ... display 2
{% else %}
   ... display 3
{% endif %}
```

This determines what the output is based on the conditions. if/else supports nesting.

The `{% if %}` tag accepts the `and`, `or` and `not` keywords to judge multiple variables, or reverse the variables (not), for example:

```python
{% if athlete_list and coach_list %}
     ....
{% endif %}
```


### for tags

The `{% for %}` allows us to iterate on a sequence.
This is similar to Python's <a href="https://pythonbasics.org/for-loops/">for loop</a>.

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

Add a `reversed` to tag so that the list is reverse-iterated:

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

You can nest with the hashtag :

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

### ifequal/ifnotequal


When they are equal, the `{% ifequal %}` label displays all values:

```python
{% ifequal user currentuser %}
    <h1>Welcome!</h1>
{% endifequal %}
```

Similar to the <a href="https://pythonbasics.org/if-statements/">if-statement</a>, the `{% ifequal %}` and `{% else %}` hashtag can be used.

```python
{% ifequal section 'sitenews' %}
    <h1>Site News</h1>
{% else %}
    <h1>No News Here</h1>
{% endifequal %}
```

### include label
The hashtag allows the content of other templates to be included in the template.

Both examples contain the nav.html template:
```python
{% include "nav.html" %}
```

### Template inheritance
Templates can be reused in an inherited manner.

Let's start by creating a base.html file in the templates directory for the previous project, coded like this:

```html
<html>
  <head>
    <title>Hello World!</title>
  </head>

  <body>
    <h1>Hello World!</h1>
    {% block mainbody %}
       <p>original</p>
    {% endblock %}
  </body>
</html>
```

In the above code, the block tag, called mainbody, is the part that can be replaced.

All the tags of the `{% block %}` tells the template engine that the subtemplate can overload these parts.

Hello.html inherits base.html and replaces specific block, hello.html the modified code as follows:

```python
{% extends "base.html" %}

{% block mainbody %}
<p>base.html</p>
{% endblock %}
```

The first line of code explains that hello.html inherits the base.html file. Then the mainbody block is defined.