Django Templates Deeper: Advanced Features and Optimization Techniques

hello, Django Hey developers, today we're talking about FundamentalsYou're familiar with the basics of using templates, but now it's time to take it to the next level, use them more efficiently, and make your projects more powerful. Are you ready to take your Django skills to the next level? Let's get started!

Django Templates in Depth - Template Inheritance

One of the most powerful features of Django Templates is the Template inheritanceThis helps reduce code duplication and maintain a consistent layout.

Create a basic template

First, create a base.htmlLet's create a basic template called

<!DOCTYPE html>
<html lang="ko">
<!-- HTML5 문서의 시작을 선언하고, 주 언어를 한국어로 지정 -->

<head>
    <meta charset="UTF-8">
    <!-- 문서의 문자 인코딩을 UTF-8로 설정 -->
    <title>{% block title %}My Django Site{% endblock %}</title>
    <!-- 페이지 제목을 위한 블록. 자식 템플릿에서 재정의 가능 -->
    {% block extra_head %}{% endblock %}
    <!-- 추가적인 head 요소를 위한 빈 블록. 필요시 자식 템플릿에서 내용 추가 가능 -->
</head>

<body>
    <header>
        {% block header %}
        <h1>Welcome to My Site</h1>
        {% endblock %}
        <!-- 헤더 섹션을 위한 블록. 기본 환영 메시지 포함. 자식 템플릿에서 변경 가능 -->
    </header>

    <main>
        {% block content %}
        {% endblock %}
        <!-- 메인 콘텐츠를 위한 빈 블록. 각 페이지의 주요 내용이 여기에 들어감 -->
    </main>

    <footer>
        {% block footer %}
        <p>© 2025 My Django Site</p>
        {% endblock %}
        <!-- 푸터 섹션을 위한 블록. 기본 저작권 정보 포함. 자식 템플릿에서 수정 가능 -->
    </footer>
</body>
</html>

Using template inheritance

Now, this default template (base.html) to create a new page.

{% extends "base.html" %}
<!-- base.html 템플릿을 상속받음을 선언 -->

{% block title %}Welcome Page{% endblock %}
<!-- base.html의 title 블록을 "Welcome Page"로 대체 -->

{% block content %}
<h2>Welcome!</h2>
<p>This page was created using Django Template inheritance.</p>
{% endblock %}
<!-- base.html의 content 블록에 새로운 내용을 추가 -->

{% block extra_head %}
<style>
    h2 { color: #007bff; }
</style>
{% endblock %}
<!-- base.html의 extra_head 블록에 CSS 스타일을 추가 -->

This way, you can keep the basic structure and only modify what you need to, which is really handy, right?

Create custom template tags and filters

Not satisfied with the default tags and filters Django provides? Don't worry. We can create our own!

Create a custom filter

First, create a myapp/templatetags/custom_filters.py file and write something like this

from django import template # Import Django's template module

register = template.Library() # Create a new template tag library

register.filter # Register the add_exclamation function as a template filter
def add_exclamation(value):
    return f"{value}!"  # Add an exclamation point after a given value

@register.filter(name='multiply') # Register the multiply_by function as a filter named 'multiply'
def multiply_by(value, arg):
    return value * arg # Multiplies the given value by the number received as argument

Example of using #:
# {{ "Hello"|add_exclamation }}  -> output: Hello!
# {{ 5|multiply:3 }}  -> output: 15

# Note: To use this file, save it to your app's templatetags folder,
# template, and load it as {% load filename %}.

Now you can use this in your template:

{% load custom_filters %}
<!-- custom_filters.py 파일에 정의된 커스텀 필터들을 로드합니다. -->

<p>{{ "Hello"|add_exclamation }}</p>
<!-- "Hello" 문자열에 add_exclamation 필터를 적용합니다. 
     결과: <p>Hello!</p> -->

<p>{{ 5|multiply:3 }}</p>
<!-- 숫자 5에 multiply 필터를 적용하고 인자로 3을 전달합니다. 
     결과: <p>15</p> -->

Create a custom tag

Creating tags isn't hard either. myapp/templatetags/custom_tags.py file and open it,

from django import template
Import the template module from # Django.

from django.utils.safestring import mark_safe
# Imports the mark_safe function for rendering HTML safely.

register = template.Library()
# Create a new template tag library.

@register.simple_tag
# Register the bootstrap_alert function as simple_tag.
def bootstrap_alert(message, alert_type='info'):
    # message: Message to display in the alert.
    # alert_type: type of alert (defaults to 'info')
    return mark_safe(f'<div class="alert alert-{alert_type}">{message}</div>')
    1Create a notification div in the style of TP5T Bootstrap, and mark it as safe HTML using mark_safe.

Example of using #:
# {% bootstrap_alert "Attention!" "warning" %}
# Output: <div class="alert alert-warning">Attention!</div>

# Caution: To use this file, save it to the templatetags folder in your app,
# template, and load it as {% load filename %}.

In a template, you can use it like this.

{% load custom_tags %}
<!-- custom_tags.py 파일에 정의된 커스텀 태그들을 로드합니다. -->

{% bootstrap_alert "Beware!" "warning" %}
<!-- bootstrap_alert 커스텀 태그를 호출합니다.
     첫 번째 인자 "주의하세요!"는 알림에 표시될 메시지입니다.
     두 번째 인자 "warning"은 알림의 유형을 지정합니다.
     
     이 태그는 다음과 같은 HTML을 생성합니다:
     <div class="alert alert-warning">주의하세요!</div>
-->

Template optimization techniques

There are ways to improve performance when using Django Templates, and here are a few tips.

  1. Caching template fragments: Caching parts that don't change often is a good idea.
{% load cache %}
{# load cache template tag library #}

{% cache 500 sidebar %}
{# cache internal content with name 'sidebar' for 500 seconds #}
{# During the cache period, subsequent requests will use the saved version to improve performance #}

    
    {# This is where you put the template code that you actually want to cache #}
    {# Example: Database query results, complex calculations, etc. #}

{% endcache %}
{# Indicates the end of the cache block #}
  1. Remove unnecessary context variables: with tag to simplify complex variables.
{% with total=business.employees.count %}
{% comment %}
Use the with tag to assign the result of business.employees.count to the total variable
This is useful when you want to run a complex calculation or database query only once and reuse the results
{% endcomment %}

    {{ total }} employee{{ total|pluralize }}
    {# Print the value of the total variable #}
    {# Use the pluralize filter to add an 's' if total is greater than 1 #}
    {# Example: 1 employee, 2 employees, 0 employees #}

{% endwith %}
{# with Indicates the end of the block. The total variable cannot be used after this #}
  1. Minimize database queries: Be careful when using iterations in templates - process data in the view beforehand if possible.

Security considerations

Django Templates automatically escape by default to prevent XSS attacks, but the safe Use caution when using filters.

{{ user_input|safe }}  

Finalize

We've dived into the depths of Django Templates, but what did you think? Template inheritance, custom tags and filters, and optimization techniques. With these features, you'll be able to create more powerful and efficient Django applications. Keep experimenting and practicing. We hope you enjoyed learning about the advanced features of Django Templates, and that your Django projects are about to get even better. Go for it!

# Glossary

  • Template inheritanceA technique for creating a base template and extending it in other templates.
  • Custom tags/filtersTemplate tags or filters created by the developer
  • Context: A set of variables passed to the template
  • EscapeTechniques to prevent XSS attacks by converting special characters to HTML entities
  • CachingA technique for pre-storing frequently used data to improve performance
테리 이모티콘
(Happy coding!)

Similar Posts