Background#As part of my ongoing project to reimplement Django’s templating language in Rust, I have been adding support for custom template tags.The simplest custom tag will look something like:# time_tags.py from datetime import datetime from django import template register = template.Library() @register.simple_tag def time(format_string): now = datetime.now() return now.strftime(format_string) # time_tags.py from datetime import datetime from django import template register = template.Library() @register.simple_tag def current_time(format_string): return datetime.now().strftime(format_string) This can then be used in a Django template like:{% load time from time_tags %} <p>Time: {% time '%H:%M:%S' %}</p> {% load current_time from time_tags %} <p>The time is {% current_time '%H:%M:%S' %}</p> The context#Django’s templating language uses an object called a context to provide dynamic data to the template renderer. This mostly behaves like a Python dictionary.detailsTechnically, Django’s context contains a list of dictionaries. This allows for temporarily changing the value of a variable, for example within a {% for %} loop, while keeping the old value for later use.A simple tag can be defined that takes the context as the first variable:# time_tags.py from datetime import datetime from django import template register = template.Library() @register.simple_tag( takes_context=True) def time(context, format_string): timezone = context["timezone"] now = datetime.now(tz=timezone) return now.strftime(format_string) # time_tags.py from datetime import datetime from django import template register = template.Library() @register.simple_tag(takes_context=True) def current_time(context, format_string): timezone = context["timezone"] return datetime.now(tz=timezone).strftime(format_string) Django Rusty Templates#In Django Rusty Templates, I have defined a context as a Rust struct. Here’s a simplified version:pub struct Context { context: HashMap< String, Py<PyAny>>, } pub struct...
First seen: 2025-09-03 14:56
Last seen: 2025-09-03 17:56