Create Template in Django

What is a template in django?

In django, A template is a HTML file which we will be using to display output on the web browser. In the .html file, we have to show some dynamic data which python will provide us. So now we have to show the html design along with the python data. This is achieved using the render() function in django. 

The render() takes 3 parameters.

  1. The first parameter is the "request". This is the initial request.
  2. The second parameter is the path of the template.
  3. The third parameter is a dictionary through which we will be sending our python data

Open the views.py file present in our app folder and add the following code:

def index(request):
    funda = ['funda','of','web','IT']
    data = "3214"
    return render(request, 'accounts/index.html', {'data':data, 'funda':funda})

As shown above, we can create a variable and store any data in a variable a pass it in the render() in a dictionary format. In the above example, we have assigned a static value "3214". We can assign any data value to a variable.For example: We can fetch data from database and store in a variable, datetime() function which will send the current time,etc.

How to render the data values in the templates?

To render/display the variables in the templates, we use the double open-close curly braces "{{ }}".

Example: {{variablename}}

As we saw the example of the views.py file, how to send the data to the template. Now lets us see the index.html.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Funda Django</title>
    <style>
        body {
            background-color: lightblue;
        }
    </style>
</head>

<body>
    <h1>This is a HTML page</h1>
    {{data}}
    <h1>{{data}}</h1>
    <p>This is a paragraph tag</p>
</body>

</html>

Now run your project and the output will be as shown below:


Tags

Tags are used to write the python code in the html file. We use the tags to perform templates inheritance, IF statement, for loop, and many other things.

We can also send array data and display it using the for loop in the tag.

Tags are written as {% %}

Example:

<body>
    <h1>This is a HTML page</h1>

    {% if data == "3214" %}
        The condition is true
    {% else %}
        The condition is false 
    {% endif %}
    <h1>{{data}}</h1>
    <p>This is a paragraph tag</p>
 
{% for info in funda %} <!-- info is the variable name-->
        {{info}} <br>
    {% endfor %}

</body>

The output for the above code will be as shown below:

Tags: Funda of web it Django tutorials, Django tutorials, Django tutorials funda, django for beginners, how to inherit template in django, templating in django, how to extend main template to all template in django