Home >>Django Tutorial >Django Templates

Django Templates

Django Templates

In Django, the template is used to generate dynamic HTML pages. A template consists of static parts of the desired HTML output as well as some special syntax that describe how the dynamic content will be inserted.

Why Django Template?

We can't write python code in HTML because the code is only interpreted by python interpreter not the browser. Django template engine is used to separate the HTML design from the python code and allows us to build dynamic web pages.

The Render Function

This function takes three different parameters −

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

Django Template Configuration

We have to provide some entries in settings.py file to configure the template system.

TEMPLATES = [  
    {  
        'BACKEND': 'django.template.backends.django.DjangoTemplates',  
        'DIRS': [os.path.join(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',  
            ],  
        },  
    },  
]  

Django Template Language (DTL)

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

Displaying Variables

The template replaces the variable with the variable sent by the view in the third parameter of the render function.

//hello.html

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

//Now our view will change like this:

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

After accessing the URL/myapp/hello we will get the following output :


Hello World!!!
Today is May. 21, 2020

If the variable is not a string then the Django will use the __str__ method to display it and using the same principle we can also access an object attribute just like the Python.

Filters

Filters help us in modifying the variables at display time. Filters structure looks like this: {{var|filters}}.

Some examples −

  • {{string|truncatewords:80}} −This filter will truncate the string so that we will see only the first 80 words.
  • {{string|lower}} – This filter will convert the string to the lowercase.
  • {{string|escape|linebreaks}} – This filter will escape the string content then convert the line breaks to tags.