Computer scienceBackendDjangoTemplates

Template tags

6 minutes read

Django, a robust Python web development framework, provides helpful tools for creating dynamic and interactive templates. This is one of the things that Django tags can help us with. It is also essential to understand how to secure your forms and requests. Let's learn more about where and how we can use template tags!

Conditions

Tags are special constructions embraced in the operators {% and %}. They can help you process parts of your template or include external resources like predefined HTML code or even other templates.

With controlling statements, we can choose what we show or do on the page depending on the conditions.

Just like in Python, branching in DTL consists of if, elif, and else statements. Curly brackets with the percent sign {% and %} embrace them and all the other tags: tags differ from variables syntactically. All branches start with {% if %} and end with {% endif %} statements.

Let's get back to our example: we've notified John that we used his first post as an example for our topic, so he made the following entry with the link to our site. The post's text speaks for itself, so John does not add a theme. He wants to retain the layout of a page, and if there's no theme, the header will be No theme as well:

<html>
  <body>
    <h3>
      {% if post.theme %} 
          Theme: {{ post.theme }}
      {% else %} 
          No theme
      <!-- Without the closing tag the whole expression is not correct -->
      {% endif %}
    </h3>
    <a href="https://hyperskill.org">How to make a post entry with Django</a>
  </body>
</html>

If you don't have a variable when you get access to a value, it's not a grave mistake. The rule is if we do not pass a variable in the context, the value of this variable is None by default.

Be cautious if you want to access attributes and methods of None — this will cause an error.

Some tags like {% if %} and {% endif %} need opening and closing parts to work correctly; others don't. Please refer to the documentation for more information about tags.

Loops

Sometimes we don't know how many items we've got on a list, but we still want to show all of them one by one on a page. Loops are helpful when you have to iterate over many similar elements.

The template loops are similar to Python for expressions. Start one with {% for %} and end it with the {% endfor %} statements.

For example, look at the comment section under John's first post: he's getting somewhere! Let's render all comments to the post one after another:

<html>
  <body>
    {% for comment in post.comments %}
      <div>Comment #{{ forloop.counter }}: {{ comment }}</div>
    {% endfor %}
  </body>
</html>

forloop is the context variable provided by Django only as part of a for loop when rendering templates. It provides information about the current iteration of the loop, allowing developers to control logic based on this information.

To access the index of the element, use the following:

  • {{ forloop.counter0 }} for zero-based iteration (it means that the indexes take values 0, 1, 2, ...)
  • {{ forloop.counter }} for one-based (the indexes take values 1, 2, 3, ...)

CSRF token

To send data to the server, we use HTML forms. Users can send confidential data and make financial transactions through forms, so we should secure the forms from potential spoofing.

Let's create a template to add comments to posts. Saving comments in handlers is too much for now, so let's prepare a section that we'll include later when we learn how to process requests on the server:

<form action="/comment/save" method="post">
  {% csrf_token %}
  <input name="text">
  <input type="submit" value="Save">
</form>

If you look closely at the code snippet, you'll surely notice a tag {% csrf_token %}. CSRF stands for Cross-Site Request Forgery. We don't want any fraud, so in forms, we must always use this tag to secure our applications. CSRF token is a generated sequence of symbols that the server uses to identify the user's session. If the sequence matches, the form is considered reliable.

Including CSRF tokens in the POST requests is obligatory in Django by default. You can turn off the verification in your handlers, but it's highly recommended to keep it.

We can face many more security issues in our web applications, but with the CSRF token, we'll have one issue less to think about.

Other useful tags

Sometimes we have several variables, but only one needs to be displayed. For example, we need to show the post's author determined by the post.author variable; if they're not defined, the blog's author is determined by the blog_author variable, and if they're not defined too, we need to show the Unknown author title. The firstof template tag can help us. It is used to output the first non-empty variable from a list of variables. It takes multiple arguments and returns the first argument's value that is not empty or False. If all arguments are empty or False, it will return an empty string. Let's see how it works:

{% firstof post.author blog_author "Unknown author" %}

If we have only one variable to check, we can use the default template filter. It is used to specify a default value for a variable if it is not defined or is empty:

{{ post.author|default:"Unknown author" }}

Finally, when we have a boolean variable, we may need to display different information depending on its value. Suppose you have an actual field that is True if the post in the blog is actual and False if it's not. We can make a condition to show the information, but there is an easier way: the yesno template filter displays different outputs based on a given value (usually a boolean or a string that can be interpreted as a boolean). It takes three arguments: the value to be evaluated, the output if the value is True, and the output if the value is False. In our case, we only need to write:

This post is {{ post.actual|yesno:"actual,too old"}}

Conclusion

In this topic, we learned how to use template tags for creating conditional statements and loops. These tools will prove to be extremely valuable as your project expands. Additionally, it is vital to consider security by adding CSRF tokens to forms in order to secure user sessions.

3 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo