Social Icons

Friday, July 3, 2020

Django Template

Django provides an efficient and convenient way to generate and display dynamic HTML pages using its template system. A template consists of a static part for HTML output, as well as a special syntax describing how dynamic content will be inserted. In an HTML file, we cannot write python code because the code is only interpreted by the python interpreter and not by the browser. We know that HTML is a static markup language, while Python is a dynamic programming language, for that we have to go through the template post.

 1 - Configuration of the django template system

Before configuring the template system, you must first:
  1. Create a directory named templates at the root of your project 
  2. Create an index.html file in the ‘templates’ directory
mysite/templates/index.html

<html>
  <head>
    <title>title</title>
  </head>
  <body>
<h2>Displaying a content via the system template !!!</h2>
    <p>MyBody</p>
  </body>
To configure the template system, we must provide certain entries in the mysite/settings.py file:
mysite/settings.py
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',  
            ],  
        },  
    },  
]
This code tells the django system that the template directory is ‘templates’ by default.

2 - Loading the template 

To load the template in a django application, just call it in the views.py file via the get_template() method: myapp/views.py
myapp/views.py 
from django.shortcuts import render  
#importing loading from django template  
from django.template import loader  
# Create your views here.  
from django.http import HttpResponse  
def index(request): 
        # getting our template
        template = loader.get_template('index.html')
        # rendering the template in HttpResponse  
        return HttpResponse(template.render())

3 - django template variables 

The Django template system uses specific syntax to use and manipulate variables, tags, expressions, etc. Template variables are accessible by {{ }} (double braces).

Example. (for a name variable with the value name='Houssam')

Welcome {{name}}
Which displays after execution: Welcome Houssam

4 - Example of a django template variable 

Template variables are declared in the views.py file and displayed in the index.html file of the template.

Example myapp/views.py 

from django.shortcuts import render
#importing loading from django template
from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index (request):
     template = loader.get_template ('index.html') # getting our template
     data = {
         'Institute': 'CRMEF OUJDA'
     }
     # rendering the template in HttpResponse
     return HttpResponse (template.render (data))
The variable 'Institute' can now be called at the level of the index.html file of the template: myapp/templates/index.html
<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="UTF-8">  
    <title>Index</title>  
</head>  
<body>  
<h2>Content displayed through the system template !!!</h2>  
<h3>Welcome to : {{ Institute }}</h3>  
</body>  
</html>
Which displays at the output:

5 - System template tags 

 In a template, tags provide logic in the rendering process. A template tag can be used in the following cases:
  1. to produce content, 
  2.  serve as a control structure (an if statement or for a loop), 
  3.  retrieve content from a database 
  4. allow access to other model tags.

Syntax :

Template tags are surrounded by:
{% and %}
and can contain any type of structure and variable.

5.1 - Case of the conditional structure if

{% if condition%}
Results display
{% else%}
other results
{% endif%}

Example. structure if… else… 

We define an age variable in the myapp/views.py file:   
myapp/views.py
from django.shortcuts import render
#importing loading from django template
from django.template import loader
# Create your views here.
from django.http import HttpResponse
def index(request):
    template = loader.get_template('index.html') # getting our template
    Age = {
        'age':14,
    }
    # rendering the template in HttpResponse
    return HttpResponse(template.render(Age))
We apply the conditional structure If… Else… at the level of the file myapp/templates/index.html 
myapp/templates/index.html
<html>
<head>
     <meta charset = "UTF-8">
     <title> Index </title>
</head>
<body>
<h2> Major and minor test! </h2>
<h3> {% if age <18%} </h3>
<p> Your age is: {{age}} you are minor ! </p>
     {% else%}
<p> Your age is: {{age}} you are major! </p>
     {% endif%}
</body>
</html>

5.2 - The For… End For tag

The for tag allows us to cycle through a sequence. We can use the for tag to execute repeated instructions, to browse the contents of a list, a tuple, a dictionary, etc. Here is the syntax of the for tag:
{% for x in list%}
The value of x is: {{x}} 
{% endfor%}

5.3 - Comments tag

The django template system also allows you to manage comments using the following syntax:
{# This is a single line comment #}
Comment you write using this syntax will not be rendered in the HTML source code. In addition, you cannot expand this comment on multiple lines. For example:
{# This is not
a comment !#}
In order to be able to write comments on several lines, we use the following syntax:
{% comment %}
This is a comment
in multiple  
lines!
{% endcomment %}



Younes Derfoufi
my-courses.net

No comments:

Post a Comment

Category Of Mobile Courses

Actualités (644) Adsense (1) Affiliation (1) Algebraic Topology (1) Algorithmic (1) all-news (30) Android (5) Android App (8) Android app without code (4) Android Apps (168) Android Development (4) Android download (2) Android OS (3) AngularJS (1) Automata theory and formal language (5) C programming (5) Category and Functor (8) CMS (3) Computer Glossary (18) Create Mobile App With Ionic Framework (2) CSS (2) CSS-Cascading-Style-Sheets (4) Developpement Java (13) Differential Geometry (1) Django-Python-Framework (8) dropshiping (26) Earn Money by Internet (4) Emplois (23) Framework php (2) Fraud (2) HTML (7) Java For Beginners (10) Javascript (12) Kotlin Programming Language (8) Kotlin For Mobile Android (1) Linux Download (2) Marketing (5) Mobile (3) Mobile Courses (4) Mobile Marketing (4) MoneyGram (1) News (721) Node.js (5) Open Source (1) Photoshop (1) Protect Computer (1) Python (33) Python BeautifulSoup (1) Python For Data Science (2) Python-Books (6) Python-DVD-Training (1) Python-Exercises (138) Python-Framework (1) Python-IDE (1) Python-Modules (1) Python-pdf (2) Python-pyQt (1) Référencement (2) Script PHP (2) Security (6) SEO (1) Snipping Tool: Faq (1) Social Networks (1) Source Code (1) Statistics With SPSS (2) Surveillance Software (1) Travail à domicile (6) Tutoriels php en vidéos (2) Tutoriels-MySql (6) tutoriels-php (19) Utilitaires (1) VPS (1) Web Hosting (1) Webcam (1) Webmarketing (11) Western Union (1) Windows 10 (1) Windows 7 (4) Windows 7 Faq (2) Windows 8 (1) Windows Accessories (1) Windows Download (8) Windows Drivers (1) Windows Fonts (1) Windows Power Shell (2) Windows Registry (2) Windows Security (18) Windows Software (2) Windows Spyware (2) Windows utilities (3) Windows Virus (2) Windows Vista (3) Windows Wireless (1) Windows xp (1) Wordpress (1)
 

Sample text

Sample Text

 
Blogger Templates