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.
The HTML code that will be generated is as follows
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 {%%}.
In our case, when we send the value 15 to the generated template, the code that is used is as follows:
Looping in a template
Step 4 : Looping allows you to read through the elements of a table or data dictionary.
With our sample data, this code will produce the following HTML code:
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:
This code generates the following HTML code:
Step 6 : The code for the upper filter is as follows:
This code generates the following HTML code:
Step 7 : The capfirst filter transforms the first letter to uppercase
This code generates the following HTML code:
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 " ...".