Created
January 23, 2024 11:29
-
-
Save alexkiro/ec66ec6d79abd481f1e54fa9a8f48b3e to your computer and use it in GitHub Desktop.
Class based template registry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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