Django Web Framework includes many tags used to create arbitrary logic in the template. Tags are used in the rendering process to give arbitrary logic. A tag can, for example, print material, act as a control structure (e.g., an “if” statement or a “for” loop), retrieve content from a database, or even give other template tags access.

Django Template Tags usage

 {%% tag %%} 

Some generate text in the output, while others manage flow with loops or logic, and still, others load external data into the template for later variables to use.

The syntax is as follows:

{%% tag_name %%}

Tags are surrounded by {% and %} like this:

{%% csrf_token %%}

Most tags accept arguments, for example :

{%% cycle 'even' 'odd' %%}

The following are tags that are frequently used in Django Templates.

Comment

Everything between {% comment %} and {% endcomment %) is ignored by the Comment Template. In the first tag, you can include an optional note. For example, it is useful when commenting out code to document why it was disabled.
Example:

{%% comment "Optional note" %%}

Commented out text with {{ create_date|date:"c" }}

{%% endcomment %%}

cycle

Each time this tag is met, it produces one of its arguments. The first argument is generated at the first interaction, the second during the second encounter, etc. When all of the arguments have been used up, the tag returns to the first argument and outputs it again. This tag is beneficial in a loop.

{%% for o in some_list %%}
	<tr class="{%% cycle 'row1' 'row2' %%}">
		...
	</tr>
{%% endfor %%}

For each loop iteration, the first iteration creates HTML that refers to class row1, the second to row2, the third to row1, and so on.

Extends

In Django, the extends tag is used for template inheritance. The same code has to be repeated over and over. We can inherit templates and variables using extends.
Example:
Assume the directory structure is as follows:

dir/
    template.html
    base.html
    secondary/
        sub_base.html
main_base.html

In template.html, we include the following paths that would be valid:

{%% extends "./base.html" %%}
{%% extends "../main_base.html" %%}
{%% extends "./secondary/sub_base.html" %%}

if

The {% if %} tag evaluates a variable and outputs the contents of the block if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value). Example:

{%% if students_list %%}
	Number of students: {{ students_list|length }}
{%% elif student_in_locker_room_list %%}
	Students should be out of the locker room soon!
{%% else %%}
	No students.
{%% endif %%}

If students_list is not empty, the student list|length variable is used to display the number of students. As can be seen, if a tag can contain one or more {% elif %} clauses, as well as a {% else %} clause, that will be displayed if all other conditions are met. These clauses are not required.

for loop

For each item in an array, the for loop for tag repeats over it, making the item available in a context variable.To display a list of students specified in students_list, for example:

<ul>
{%% for studnet in students_list %%}
	<li>{{ student.name }}</li>
{%% endfor %%}
</ul>

for … empty loop

For each item in an array, the for… empty loop for tag runs over it, making the item available in a context variable. It is mainly used as a condition to be checked to see if the queryset is empty and, if so, what action is taken. If the specified array is empty or cannot be found, the tag can take an optional {% empty %} clause, whose content is displayed.

<ul>
{%% if students_list %%}
	{%% for student in students_list %%}
	<li>{{ student.name }}</li>
	{%% endfor %%}
{%% else %%}
	<li>Sorry, no students in this list.</li>
{%% endif %%}
</ul>

Boolean Operators (Operators with Boolean Values )

The {% if %} tag evaluates a variable and outputs the contents of the block if the variable is “true” (i.e. exists, is not empty, and is not a false boolean value). With the Django If Template tag, you can employ a variety of boolean operators.

<ul>
{%% if variable boolean_operator value %%}
// statements
{%% endif %%}
</ul>

The use of parentheses in the if the tag is incorrect syntax. You should use nested tags if you need to indicate precedence. The operators ==,!=, >, =, >=, in, not in, is, and is not can also be used in if tags.

Complex expressions

Complex expressions are created by combining all of the above. Understanding how the operators are grouped when the expression is evaluated or the precedence rules for such expressions. The following is the order of the operators, from lowest to highest:

  • or
  • and
  • not
  • in
  • ==
  • !=
  • <
  • >
  • <=
  • >=

This is exactly how Python works. For instance, consider the following complex if tag: {% if x == y or w == z and e %} can further be interpreted as (x == y) or ((w == z) and e). You’ll need to use nested tags if you need alternative precedence. Just in case the precedence rules are unfamiliar, this is sometimes preferable for clarity.

In contrast to Python and mathematical notation, the comparison operators cannot be ‘chained.’ For instance, instead of saying: {% if x > y > w %} we opt to use {% if x > y and y > w %}

firstof

The first parameter variable that isn’t “false” is output (i.e. exists, is not empty, is not a false boolean value, and is not a zero numeric value). If all of the given variables are “false,” nothing is returned.

{%% firstof firstVar secondVar thirdVar %%}

The preceding code is similar to the following code:

{%% if firstVar %%}
    {{ firstVar }}
{%% elif secondVar %%}
    {{ secondVar }}
{%% elif thirdVar %%}
    {{ thirdVar }}
{%% endif %%}

If all of the given variables are False, a literal string can be used as a backup value:

include

The include tag loads and produces a template using the current context. It is a technique for “incorporating” other templates into a template. A variable or a hard-coded (quoted) text in single or double quotes can be used as the template name.

The include tag is interpreted as “render this subtemplate and include the HTML,” rather than “parse this subtemplate and include its contents as if it were a child of the parent.” It means that there is no common state between included templates; instead, each include renders independently.

Before a block is included, it is reviewed. It means that a template containing blocks from another template will have blocks that have already been assessed and rendered, rather than blocks that can be altered by an extending template, for example.

{%% include "students/registration.html" %%}

Usually, the template name is relative to the root directory of the template loader. As the extends tag explains, a string argument can also be a relative route beginning with./ or../.

lorem

The lorem tag displays a random Latin text, “lorem ipsum.” It is used to provide sample data in templates.

  • {% lorem %} will output the ordinary “lorem ipsum” paragraph.
  • {% lorem 3 p %} will output the typical “lorem ipsum” paragraph and two random paragraphs, each wrapped in HTML tags.
  • {% lorem 4 w random %} is responsible for displaying four random Latin words.

now

The now tag shows the current date and time in the format specified by the string. As the date filter section explains, such a string can contain format specifiers characters.

It is {%% now "D d M Y" %%}

url

url tag Returns an absolute path reference (a URL that does not include the domain name) that matches a given view and optional parameters. It is a way to produce links without hard-coding URLs in your templates, violating the DRY principle.

{%% url 'test-url-name' v1 v2 %%}

The first argument is the name of a URL pattern. It could be a quoted literal or a context variable of any kind. Optional additional arguments should be space-separated values utilized as arguments in the URL. The preceding example demonstrates how to pass positional arguments. You can also use keyword syntax, which is as follows:

{%% url 'test-url-name' arg1=v1 arg2=v2 %%}

In a single call, do not use both positional and keyword syntax. The URLconf expects all arguments to be present.

Ifchanged

Check if a value has changed since the last loop iteration. Within a loop, the (% ifchanged %} block tag is utilized. It is used in two ways.

It compares its rendered content to its initial state and only shows if it has changed. This, for example, shows a list of days, with the month only changing if it changes:

<h1> {{ year }}'s Archive</h1>

{%% for date in days %%}
    {%% ifchanged %%}<h3>{{ date|date:"F" }}</h3>{%% endifchanged %%}
    <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
{%% endfor %%}

If you’re given one or more variables, see if any of them have changed. The following, for example, displays the date whenever it changes, as well as the hour if either the hour or the date has changed:

{%% for date in days %%}
    {%% ifchanged date.date %%} {{ date.date }} {%% endifchanged %%}
    {%% ifchanged date.hour date.date %%}
        {{ date.hour }}
    {%% endifchanged %%}
{%% endfor %%}

If the value has not changed, the ifchanged tag can also take an optional {% else %} clause, which will be displayed:

{%% for match in matches %%}
    <div style="background-color:
        {%% ifchanged match.ballot_id %%}
            {%% cycle "green" "yellow" %%}
        {%% else %%}
            orange
        {%% endifchanged %%}
    ">{{ match }}</div>
{%% endfor %%}

load

It loads a set of customized template tags. For example, the template below is responsible for loading all of the tags and filters registered in the package’s somelibrary and otherlibrary:

{%% load somelibrary package.otherlibrary %%}

The argument is used to load certain filters or tags from a library. The template tags/filters ‘foo bar’ is loaded from somelibrary in this example:

{%% load foo bar from somelibrary %%}

regroup

A common attribute is used to regroup a list of similar items. An example of this complex tag might be as follows: Suppose cities is a list of cities represented by dictionaries with keys for “name,” “population,” and “country”:

cities = [
{'city_name': 'London', 'population': '19,000,000', 'country': 'UK'},
{'city_name': 'Manchester', 'population': '15,000,000', 'country': 'UK'},
{'city_name': 'New York', 'population': '20,000,000', 'country': 'USA'},
{'city_name': 'Los Angeles', 'population': '7,000,000', 'country': 'USA'},
{'city_name': 'London', 'population': '33,000,000', 'country': 'Japan'},
]

Group the list of cities by country i.e.; you’d like to show a country-ordered hierarchical list, use the {% regroup %} tag. It is done with the following snippet of template code:

{%% regroup cities by country as country_list %%}

<ul>
{%% for country in country_list %%}
    <li>{{ country.grouper }}
    <ul>
        {%% for city in country.list %%}
          <li>{{ city.name }}: {{ city.population }}</li>
        {%% endfor %%}
    </ul>
    </li>
{%% endfor %%}
</ul>

The command {% regroup %} requires three arguments: the list to regroup, the attribute to group by, and the name of the resulting list. We’re calling the output country_list after regrouping the cities list by the nation property.

{% regroup %} returns a list of group objects (in this case, country_list). Group objects are namedtuple() instances with two fields:

grouper

The item that was grouped by (for example, the string “India” or “Japan”) is known as the grouper. list – a list of all objects in this group (for example, a list of all cities in UK).
Because {% regroup %} returns namedtuple() objects, the preceding example can be be written as:

{%% regroup cities by country as country_list %%}

<ul>
{%% for country, local_cities in country_list %%}
    <li>{{ country }}
    <ul>
        {%% for city in local_cities %%}
          <li>{{ city.name }}: {{ city.population }}</li>
        {%% endfor %%}
    </ul>
    </li>
{%% endfor %%}
</ul>

It’s worth noting that {% regroup %} does not sort its input! Our example is based on the fact that the cities list has initially been sorted by country. If the cities list didn’t sort its members by country, the regrouping would show many groups for a single country.

resetcycle

Resets a previous cycle so that the next encounter begins with the initial item. { % resetcycle %} will reset the last {% cycle %} defined in the template if no arguments are provided.

{%% for coach in coach_list %%}
    <h1>{{ coach.name }}</h1>
    {%% for athlete in coach.athlete_set.all %%}
        <p class="{%% cycle 'odd' 'even' %%}">{{ athlete.name }}</p>
    {%% endfor %%}
    {%% resetcycle %%}
{%% endfor %%}

autoescape

autoescape is a variable that controls the current auto-escape behaviour. This tag accepts two arguments: on or off, which specifies whether auto-escaping is enabled inside the block. An endautoescape finishing tag is used to finish the block.

When auto-escaping is enabled, all variable content is subjected to HTML escaping. Before being sent to the output, it happens after any applied filters. It is the same as using the escape filter for each variable by hand.

The only exceptions are variables that have already been declared “safe” from escaping, either by the code that populated the variable or by the safe or escape filters.

{%% autoescape on %%}
    {{ body }}
{%% endautoescape %%}

filter

Apply one or more filters to the contents of the block. Pipes can specify many filters that contain arguments, exactly like variable syntax. The textual information between the filter and endfilter tags is included in the block.

{%% filter force_escape|upper %%}
    Contents here are HTML-escaped, and will appear in all upercase.
{%% endfilter %%}

templatetag

Returns one of the syntax characters used to make template tags. Individual characters cannot be “escaped” under the template system. The { % templatetag %} tag, on the other hand, can be used to display one of the template tag character combinations.

The template bit to output is specified by the argument:

ArgumentOutputs
openblock{%
closeblock%}
openvariable{{
closevariable}}
openbrace{
closebrace}
opencomment{#
closecomment#}



The {% templatetag openblock %} characters is responsible for opening a block.

With

Caches a complex variable beneath a more straightforward name. This is handy when visiting an “expensive” method (e.g., one that queries the database) several times.

{%% with total=codeunderscored.employees.count %%}
{{ total }} employee{{ total|pluralize }}
{%% endwith %%}

Between the {% with %} and {%endwith %} tags, the populated variable (in the example above, total) is only available. More than one context variable can be assigned:

{%% with alpha=1 beta=2 %%}
    ...
{%% endwith %%}

verbatim

The template engine does not render this block tag’s contents. Allowing a JavaScript template layer that clashes with Django’s grammar is a typical use. Consider the following scenario:

{%% verbatim %%}
    {{if duty}}Working on  Python. {{/if}}
{%% endverbatim %%}

You can also specify a custom closing tag, which allows you to use {% endverbatim% }as part of the unrendered contents:

{%% verbatim myblock %%}
    template rendering is avoided via the {%% verbatim %%}{%% endverbatim %%} block.
{%% endverbatim myblock %%}

widthratio

This tag will handle the ratio calculation of a given value to a maximum value and then applies that ratio to a constant to create bar charts and other graphs. Consider the following scenario:

<img src="logo.png" alt="logo"
     height="10" width="{%% widthratio this_value max_value max_width %%}">

In some circumstances, you may want to store the widthratio result in a variable. It could come in handy in a blocktranslation as follows:

{%% widthratio this_val max_val max_width as width %%}
{%% blocktranslate %%}The width is: {{ width }}{%% endblocktranslate %%}

Reference to the built-in filter

add

The argument is added to the value.

Consider the following scenario:

{{ value|add:"3" }}

The output will be ten if the value is seven. The initial step in this filter is to convert both values to integers. If this fails, it will attempt to combine the values anyhow. Some data types (strings, lists, etc.) will work, but others will fail. The result will be an empty string if it fails.

For instance, suppose we have:

{{ first|add:second }}

The output will be [11, 12, 13, 14, 15, 16] if the first is [11,12, 13] and the second is [14, 15, 16]. As in the first example, strings converted to integers will be added together rather than concatenated.

addslashes

Before quotations, slashes are added. For example, in CSV, this is useful for escaping strings. Consider the following scenario:

{{ value|addslashes }}

The output will be “I\’m browsing codeunderscored.com” if the value is “I’m browsing codeunderscored.com Django.”

capfirst

The first character of the value is capitalized. This filter has no effect if the first character is not a letter. Consider the following scenario:

{{ value|capfirst }}

The result will be “Codeunderscored” on the off chance that the value is “codeunderscored”.

Center

Center is a function that centers the value in a field of a specific width. Consider the following scenario:

"{{ value|center:"20" }}"

The output will be ” Codeunderscored “.If the value is “Codeunderscored”,,.

cut

All parameter values are removed from the provided string. Consider the following scenario:

{{ value|cut:" " }}

The output will be “www.codeundercored.com”, if the value is “www. codeunderscored. com”.

date

Formats a date in the specified format. Certain modifications use a format comparable to PHP’s date() function. Outside of templates, Django does not use these format characters. They were created to be compatible with PHP to make the transition for designers as painless as possible.

default

If the value evaluates to False, the default is used. Otherwise, the value is used. Consider the following scenario:

{{ value|default:"nothing" }}

The output will be nothing If the value is ” ” (the empty string).

default_if_none

Uses the supplied default if (and only if the) value is None. Otherwise, the value is used. The default value is not utilized if an empty string is provided. Use the default filter if you wish to fall back on empty strings. Consider the following scenario:

{{ value|default_if_none:"nothing" }}

The output will be nothing If the value is None.

Conclusion

When creating the presentation layer of your Django project, the Django template language comes with several built-in tags and filters. This tutorial has shown you how to use some of the standard template tags and filters in Django and use them in templates. We hope this helps to achieve your objectives.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *