Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Django Template Syntax: Variables, Filters, Tags, and Custom Extensions

Tech May 15 16

1. Core Syntax

Django templates use two key syntax patterns:

  • {{ }} for variable interpolation
  • {% %} for logical operations (loops, conditions, etc.)
# views.py
from django.shortcuts import render
import datetime

def get_current_timestamp(request):
    profile = {"username": "moon", "age": 22}
    current_datetime = str(datetime.datetime.now())
    return render(request, "timestamp.html", {"current_time": current_datetime, "profile": profile})
<!-- timestamp.html -->
<h1>{{ current_time }}</h1>
<h1>{{ profile.username }}</h1>
<h1>{{ profile.age }}</h1>

<!-- Output -->
<!-- 2025-03-10 14:25:30.123456 -->
<!-- moon -->
<!-- 22 -->

2. Variable Usage

The dot notation is central to accessing nested data structures in Django templtaes. Syntax: {{ variable_name }}

# views.py
def display_index(request):
    sample_dict = {2: 4, "title": "moon"}
    
    # Method 1: Explicit context
    return render(request, "index.html", {"data_dict": sample_dict})
    
    # Method 2: Local variables (includes all variables in scope)
    return render(request, "index.html", locals())

# Supported data types to pass to templates
text = "Hi there!"
numbers = [3, 5, 7, ["x", "xyz"]]
sample_dict = {2: 4, "title": "moon"}
coords = (10, 20, 30)
distinct_values = {1, 3, 5, 7}

def greet_user():
    return "Welcome back!"

class Product:
    def __init__(self, name, price):
        self.product_name = name
        self.price = price
    
    def get_discount_price(self):
        return self.price * 0.9

product_obj = Product("Laptop", 999.99)

Variable Types & Access Methods

Type View Definition Template Access Examples Output
String text = "Hi there!" {{ message }} Hi there!
List numbers = [3,5,7,["x","xyz"]] {{ num_list.1 }} {{ num_list.3.0 }} 5 x
Dictionary sample_dict = {2:4, "title":"moon"} {{ data_dict.title }} moon
Tuple coords = (10,20,30) {{ coordinates.2 }} 30
Set distinct_values = {1,3,5,7} {{ unique_values }} {1,3,5,7}
Function def greet_user(): ... {{ greet }} Welcome back!
Object product_obj = Product(...) {{ item.product_name }} {{ item.get_discount_price }} Laptop 899.991

Note: All iterable types can be looped over using {% for item in iterable %} <p>{{ item }}</p> {% endfor %}.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.