Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Other Template Tags

In this tutorial, we'll cover some of the other common template tags available in Django. Template tags are enclosed in {% %} and are used to add logic to your templates.

  1. {% for ... %}: Loop over a sequence (e.g., a list, tuple, or queryset).
  2. {% if ... %}: Evaluate a condition and display content based on the result.
  3. {% include ... %}: Include another template within the current template.
  4. {% with ... %}: Create an alias for a variable or an expression.
  5. {% comment ... %}: Add a comment that won't be displayed in the final output.
  6. {% block ... %} and {% extends ... %}: Template inheritance and content blocks.

1. Looping with {% for ... %}

Loop over a sequence of items using the {% for ... %} tag:

<ul>
{% for book in books %}
  <li>{{ book.title }} by {{ book.author }}</li>
{% endfor %}
</ul>

2. Conditionals with {% if ... %}

Use {% if ... %} to evaluate a condition and display content based on the result:

{% if user.is_authenticated %}
  <p>Welcome, {{ user.username }}!</p>
{% else %}
  <p>Please log in to access this content.</p>
{% endif %}

3. Including templates with {% include ... %}

Include another template within the current template using {% include ... %}:

{% include 'navigation.html' %}

4. Aliases with {% with ... %}

Create an alias for a variable or an expression using {% with ... %}:

{% with total=cart.items|length %}
  <p>You have {{ total }} items in your cart.</p>
{% endwith %}

5. Comments with {% comment ... %}

Add a comment in your template that won't be displayed in the final output using {% comment ... %}:

{% comment %}
  This section is reserved for future updates.
{% endcomment %}

6. Template inheritance with {% block ... %} and {% extends ... %}

Use {% block ... %} to define content blocks in a base template and {% extends ... %} to inherit from a base template in a child template.

base.html:

<!DOCTYPE html>
<html>
  <head>
    <title>{% block title %}Default Title{% endblock %}</title>
  </head>
  <body>
    <div id="content">{% block content %}{% endblock %}</div>
  </body>
</html>

child.html:

{% extends 'base.html' %}

{% block title %}Child Page Title{% endblock %}

{% block content %}
  <h1>Welcome to the child page!</h1>
{% endblock %}

In this tutorial, we've covered various other common template tags in Django, such as loops, conditionals, including other templates, aliases, comments, and template inheritance. These tags allow you to add logic and structure to your templates, making them more dynamic and flexible.

  1. Django Template Tags Beyond if and for:

    • Description: Explore advanced template tags beyond basic if and for statements for more dynamic templates.
    • Code:
      {% with total_price=item.price|add:tax|floatformat:2 %}
          Total Price: ${{ total_price }}
      {% endwith %}
      
  2. Exploring Advanced Django Template Tags:

    • Description: Dive deeper into Django's powerful template tag system for complex template logic.
    • Code: (Example using the regroup tag)
      {% regroup items by category as grouped_items %}
      {% for category in grouped_items %}
          {{ category.grouper }}
          {% for item in category.list %}
              {{ item.name }}
          {% endfor %}
      {% endfor %}
      
  3. List of Django Template Tags and Their Uses:

    • Description: Provide an overview of various Django template tags and their common use cases.
    • Code: (Generic example showcasing different tags)
      {% if user.is_authenticated %}
          Welcome, {{ user.username }}!
      {% else %}
          Please log in.
      {% endif %}
      
      {% for item in items %}
          {{ item.name }}
      {% endfor %}
      
  4. Working with Built-in Django Template Tags:

    • Description: Utilize built-in template tags like url, block, and filter for various tasks.
    • Code: (Example using the url tag)
      <a href="{% url 'app_name:view_name' param1=parameter %}">Link</a>
      
  5. Django Template Tags for Date and Time:

    • Description: Format and manipulate date and time using Django's date-related template tags.
    • Code: (Example using the date tag)
      {{ some_date|date:"F j, Y" }}
      
  6. Dynamic Template Tags in Django Examples:

    • Description: Create dynamic templates using template tags based on changing conditions.
    • Code: (Dynamic rendering based on a variable)
      {% if is_featured %}
          Featured Item
      {% else %}
          Regular Item
      {% endif %}
      
  7. Creating Reusable Template Tags in Django:

    • Description: Build and use custom template tags for code reusability.
    • Code: (Example of a custom tag)
      # custom_tags.py
      from django import template
      
      register = template.Library()
      
      @register.simple_tag
      def my_custom_tag(parameter):
          # Your logic here
          return result
      
  8. Conditional Rendering with Django Template Tags:

    • Description: Use template tags for conditional rendering based on specific conditions.
    • Code: (Conditional rendering example)
      {% if user.is_authenticated %}
          Welcome back, {{ user.username }}!
      {% else %}
          Please log in to access the content.
      {% endif %}
      
  9. Using Template Tags for String Manipulation in Django:

    • Description: Manipulate strings using template tags for tasks like slicing, concatenation, etc.
    • Code: (Example using the slice filter)
      {{ long_text|slice:":50" }}
      
  10. Django Template Tags for Handling URLs:

    • Description: Manage URLs in templates using tags like url and reverse.
    • Code: (Example using the reverse tag)
      <a href="{% url 'app_name:view_name' param1=parameter %}">Link</a>
      
  11. Pagination with Django Template Tags:

    • Description: Implement pagination in templates using Django's built-in pagination template tags.
    • Code: (Example using {% for item in items %})
      {% for item in items %}
          {{ item.name }}
      {% endfor %}
      
      {% if items.has_other_pages %}
          <div class="pagination">
              <span class="step-links">
                  {% if items.has_previous %}
                      <a href="?page=1">&laquo; first</a>
                      <a href="?page={{ items.previous_page_number }}">previous</a>
                  {% endif %}
      
                  <span class="current">
                      Page {{ items.number }} of {{ items.paginator.num_pages }}.
                  </span>
      
                  {% if items.has_next %}
                      <a href="?page={{ items.next_page_number }}">next</a>
                      <a href="?page={{ items.paginator.num_pages }}">last &raquo;</a>
                  {% endif %}
              </span>
          </div>
      {% endif %}
      
  12. Template Tags for Including Templates in Django:

    • Description: Include and reuse templates using tags like include and block.
    • Code: (Example using the include tag)
      {% include 'common/header.html' %}
      
  13. Django Template Tags for Form Handling:

    • Description: Handle forms in templates using template tags for form rendering and validation.
    • Code: (Example using the form tag)
      <form method="post" action="{% url 'app_name:view_name' %}">
          {% csrf_token %}
          {{ form.as_p }}
          <button type="submit">Submit</button>
      </form>
      
  14. Advanced Filtering with Django Template Tags:

    • Description: Use template tags for advanced filtering of lists or querysets in templates.
    • Code: (Example using the filter tag)
      {% for item in items|filter:some_condition %}
          {{ item.name }}
      {% endfor %}
      
  15. Extending Template Tags in Django:

    • Description: Extend and customize existing template tags for specific project needs.
    • Code: (Example of extending the date tag)
      # custom_tags.py
      from django import template
      from django.template.defaulttags import register
      
      @register.filter
      def custom_date(value, arg):
          # Your custom date logic here
          return result
      
  16. Template Tags for Handling Images in Django:

    • Description: Use template tags for displaying and manipulating images in templates.
    • Code: (Example using the img tag)
      <img src="{{ image.url }}" alt="{{ image.description }}">
      
  17. Django Template Tags for Content Formatting:

    • Description: Format and style content in templates using tags like linebreaks, truncatewords, etc.
    • Code: (Example using the linebreaks tag)
      {{ text|linebreaks }}