Logo

Django 3 : Passing Variables to the template

Nov 20, 2020
Django 3 : Passing Variables to the template

Injecting the data from the view to the template

Before improving our template, we must send variables to the templates. The injection of the data is based on these variables, as the template will perform certain actions

Step 1 : We will change our view to inject variables in our template. The following is our modified view:

Integrating variables in templates

Step 2 : In our controller, we send a variable named my_str. We can display it in a <span> tag in the following way.

<span> {{my_str}} </span>

The HTML code that will be generated is as follows

<span> Hello World ! </span>

Conditional statements in a template

Step 3 : Note that for a display variable, double brackets {{}} are used, but once we have an action to be made as a condition or loop, we will use {%%}.

<span>
    {% if my_num > 10 %}
        my_num is greater than 10
    {% else %}
        my_num is less than 10
    {% endif %}
</span>

In our case, when we send the value 15 to the generated template, the code that is used is as follows:

<span>my_num is greater than 10</span>

Looping in a template

Step 4 : Looping allows you to read through the elements of a table or data dictionary.

<ul>
    {% for car in my_arr %}
        <li>
            {{ car }}
        </li>
    {% endfor %}
</ul>

With our sample data, this code will produce the following HTML code:

<ul>
        
    <li>
    Honda
    </li>

    <li>
    Ford
    </li>

    <li>
    BMW
    </li>

</ul>

Using filters in a template

Step 5 : The upper, lower filters and capfirst filter

The lower filter converts into lowercase letters. The code for the lower filter is as follows:

<span> {{ my_str | lower }} </span>

This code generates the following HTML code:

<span> hello world ! </span>

Step 6 : The code for the upper filter is as follows:

<span> {{ my_str | upper }} </span>

This code generates the following HTML code:

<span> HELLO WORLD ! </span>

Step 7 : The capfirst filter transforms the first letter to uppercase

<span> {{ my_str | capfirst }} </span>

This code generates the following HTML code:

<span> Hello World ! </span>

The truncatechars filter

Step 8 : The truncatechars filter allows you to truncate a string from a certain length. If this number is exceeded, the string is truncated and Django adds the string " ...".

{{ my_str|truncatechars:5 }}