Django Template System

Django Template System

Django allows Python and HTML to be divided, the Python goes into views, and HTML goes into templates. Django relies on the render feature and the language of the Django Model to connect the two.

 Render Function

  It works on three parameters-

  • Request- it is the initial phase or request.
  • The path to the template- This is the direction in the project settings.py variables relative to the TEMPLATE DIRS option.
  • Dictionary of parameters- A dictionary containing all the appropriate variables in the model. This variable can be generated, or all local variable declared in the view can be transferred by locals()

Template Configuration

To configure the template system, we have to provide some entries in settings.py file.
 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',  
     ], }, }, ]   

 DTL (Django Template Language)

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

 Displaying Variable

This seems to be a variable: { { variable}}. The model replaces the variable in the third      parameter of the render function with the variable sent by the view. Let's update our hello.html to reveal the date of today – 

First.html
 html>
   <body>
      Hello World!!!<p>Today is {{today}}</p>
   </body>
 </html>
 View will change like this. 
 def hello(request):
    today = datetime.datetime.now().date()
    return render(request, "hello.html", {"today" : today}) 

Output

Hello World!!!
 Today is Nov. 21, 2019 

As we have noticed, if the parameter is not a string, Django will use the _str_ method to show it; and we may access an object attribute with the same concept as you do in Python. For example, my parameter would be:{{ today.year}} if we decided to show the date-time.

Filters 

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

 Examples   

{{string|truncatewords:30}} – This will truncate the string. It will show only starting 30 words.

{{string|lower}} – It will convert a string into a lower case.

{{string|escape|linebreaks}}- Escape the contents of the string, then turn line breaks into tags.

We can also set a default value for the variable.

Tags

Tags allow the following operations to be performed: if condition, loop, inheritance template, and more.

If Tag

Just like in Python, if, and else in your model, you can use it 

<html>
    <body>
       Hello Django World!!!<p>Today is {{today}}</p>
       We are here 
       {% if today.day == 1 %} 
       the first day of month.
       {% elif today.day == 30 %}
       the last day of the month.
       {% else %}
 I do not remember
       {%endif%}
    </body>
 </html> 

Tag For

Just like ' if ' we've got the ' for ' tag, it works just like in Python does. Let's switch our view to give a list to our template

hello(request):
    today = datetime.datetime.now().date() 
    daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek}) 

Tag displaying list using{{for}}

<html>
    <body>
       Hello Django World!!!<p>Today is {{today}}</p>
       {% if today.day == 1 %}
       the first day of month.
       {% elif today.day == 30 %}
       the last day of the month. 
 {% else %} 
       I not remember.
       {%endif%}
       <p> 
          {% for day in days_of_week %}
          {{day}}
       </p>
       {% endfor %}
    </body>
 </html> 

      

Output

Hello Django World!!!
 Today is Nov. 21, 2019
 I not remember
 Monday           
 Tuesday
 Wednesday
 Thursday
 Friday
 Saturday
 Sunday 

 Block And Extends Tag

Without the inheritance of the template, a template model can not be complete. In other words, when designing your templates, you should have a main template with holes to fill the child's template according to your own needs, as a site may need a special CSS for the selected section area.

Title_template.html
 <html>
    <head>
       <title>
          {% block title %}Title of page{% endblock %}
       </title>
    </head>
    <body> 
       {% block content %}
          Body content
       {% endblock %}
    </body>
 </html> 
 <p>
    {% for day in days_of_week %}
    {{day}}
 </p>
 {% endfor %}
 {% endblock % 

Hello .html

% extends
"main_template.html" %}
 {% block title %}My first Page{% endblock %}
 {% block content %}
 Hello World!!!<p>Today is thursday {{today}}</p>
 We are
 {% if today.day == 1 %} 
 the first day of month.
 {% elif today.day == 30 %}
 the last day of the month.
 {% else %}
 I don't remember
 {%endif%} 

In the above example, we will still get the same result as before when calling /myapplication / hello, but now we reallyy on extend and blocking to refactor our code

We identify frames using the label block in the main template.html. The title block contains the name of the page, and the information block contains the main content of the site. We use extend to inherit from the title_template.html in home.html; then, we fill the above-defined block (content and title).