Skip to content

Instantly share code, notes, and snippets.

@alexkiro
Created January 23, 2024 11:29
Show Gist options
  • Save alexkiro/ec66ec6d79abd481f1e54fa9a8f48b3e to your computer and use it in GitHub Desktop.
Save alexkiro/ec66ec6d79abd481f1e54fa9a8f48b3e to your computer and use it in GitHub Desktop.
Class based template registry
import re
from django import template
class BaseSimpleTag:
def __init__(self, context: dict):
self.context = context
self.request = context["request"]
def __str__(self):
return str(self.get())
def get(self):
raise NotImplementedError
class TemplateLibraryWithClasses(template.Library):
def class_simple_tag(self, cls: BaseSimpleTag.__class__):
# Convert from CamelCase to snake_case
name = re.sub("(?!^)([A-Z]+)", r"_\1", cls.__name__).lower()
def wrapper(context):
return cls(context).get()
self.simple_tag(wrapper, takes_context=True, name=name)
return cls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment