|
| 1 | +import re |
| 2 | +from typing import Any, Optional |
| 3 | + |
| 4 | +from django import template |
| 5 | +from django.db.models.base import Model |
| 6 | +from django.template import Node, TemplateSyntaxError |
| 7 | + |
| 8 | +register = template.Library() |
| 9 | + |
| 10 | + |
| 11 | +@register.simple_tag |
| 12 | +def dom_id(instance: Any, prefix: Optional[str] = "") -> str: |
| 13 | + """ |
| 14 | + Generate a unique identifier for a Django model instance, class, or even Python object. |
| 15 | +
|
| 16 | + Args: |
| 17 | + instance (Any): The instance or class for which the identifier is generated. |
| 18 | + prefix (Optional[str]): An optional prefix to prepend to the identifier. Defaults to an empty string. |
| 19 | +
|
| 20 | + Returns: |
| 21 | + str: The generated identifier. |
| 22 | +
|
| 23 | + Raises: |
| 24 | + Exception: If the model instance does not have either the `to_key` or `pk` attribute. |
| 25 | +
|
| 26 | + Note: |
| 27 | + - If `instance` is a Django model instance, the identifier is generated based on the `to_key` or `pk` attribute. |
| 28 | + - If `instance` is a Django model class, the identifier is generated as `new_<class_name>`. |
| 29 | + - If `instance` is neither a model instance nor a model class, the identifier is generated based on the `to_key` |
| 30 | + attribute if available, otherwise it uses the string representation of the instance. |
| 31 | + - The `prefix` argument can be used to prepend a prefix to the generated identifier. |
| 32 | + """ |
| 33 | + if not isinstance(instance, type) and isinstance(instance, Model): |
| 34 | + # Django model instance |
| 35 | + if hasattr(instance, "to_key") and getattr(instance, "to_key"): # noqa: B009 |
| 36 | + identifier = f"{instance.__class__.__name__.lower()}_{instance.to_key}" |
| 37 | + elif hasattr(instance, "pk") and getattr(instance, "pk"): # noqa: B009 |
| 38 | + identifier = f"{instance.__class__.__name__.lower()}_{instance.pk}" |
| 39 | + else: |
| 40 | + raise Exception( |
| 41 | + f"Model instance must have either to_key or pk attribute {instance}" |
| 42 | + ) |
| 43 | + elif isinstance(instance, type) and issubclass(instance, Model): |
| 44 | + # Django model class |
| 45 | + identifier = f"new_{instance.__name__.lower()}" |
| 46 | + else: |
| 47 | + if hasattr(instance, "to_key") and getattr(instance, "to_key"): # noqa: B009 |
| 48 | + # Developer can still use to_key property to generate the identifier |
| 49 | + identifier = f"{instance.to_key}" |
| 50 | + else: |
| 51 | + # Use the string representation |
| 52 | + identifier = str(instance) |
| 53 | + |
| 54 | + if prefix: |
| 55 | + identifier = f"{prefix}_{identifier}" |
| 56 | + |
| 57 | + return identifier |
| 58 | + |
| 59 | + |
| 60 | +ATTRIBUTE_RE = re.compile( |
| 61 | + r""" |
| 62 | + (?P<attr> |
| 63 | + [@\w:_\.\/-]+ |
| 64 | + ) |
| 65 | + (?P<sign> |
| 66 | + \+?= |
| 67 | + ) |
| 68 | + (?P<value> |
| 69 | + ['"]? # start quote |
| 70 | + [^"']* |
| 71 | + ['"]? # end quote |
| 72 | + ) |
| 73 | +""", |
| 74 | + re.VERBOSE | re.UNICODE, |
| 75 | +) |
| 76 | + |
| 77 | + |
| 78 | +VALUE_RE = re.compile( |
| 79 | + r""" |
| 80 | + ['"] # start quote (required) |
| 81 | + (?P<value> |
| 82 | + [^"']* # match any character except quotes |
| 83 | + ) |
| 84 | + ['"] # end quote (required) |
| 85 | + """, |
| 86 | + re.VERBOSE | re.UNICODE, |
| 87 | +) |
| 88 | + |
| 89 | + |
| 90 | +@register.tag |
| 91 | +def class_names(parser, token): |
| 92 | + error_msg = f"{token.split_contents()[0]!r} tag requires " "a list of css classes" |
| 93 | + try: |
| 94 | + bits = token.split_contents() |
| 95 | + tag_name = bits[0] # noqa |
| 96 | + attr_list = bits[1:] |
| 97 | + except ValueError as exc: |
| 98 | + raise TemplateSyntaxError(error_msg) from exc |
| 99 | + |
| 100 | + css_ls = [] |
| 101 | + css_dict = {} |
| 102 | + for pair in attr_list: |
| 103 | + attribute_match = ATTRIBUTE_RE.match(pair) or VALUE_RE.match(pair) |
| 104 | + |
| 105 | + if attribute_match: |
| 106 | + dct = attribute_match.groupdict() |
| 107 | + attr = dct.get("attr", None) |
| 108 | + # sign = dct.get("sign", None) |
| 109 | + value = parser.compile_filter(dct["value"]) |
| 110 | + if attr: |
| 111 | + css_dict[attr] = value |
| 112 | + else: |
| 113 | + css_ls.append(value) |
| 114 | + else: |
| 115 | + raise TemplateSyntaxError("class_names found supported token: " + f"{pair}") |
| 116 | + |
| 117 | + return ClassNamesNode(css_ls=css_ls, css_dict=css_dict) |
| 118 | + |
| 119 | + |
| 120 | +class ClassNamesNode(Node): |
| 121 | + def __init__(self, css_ls, css_dict): |
| 122 | + self.css_ls = css_ls |
| 123 | + self.css_dict = css_dict |
| 124 | + |
| 125 | + def render(self, context): |
| 126 | + final_css = [] |
| 127 | + |
| 128 | + # for common css classes |
| 129 | + for value in self.css_ls: |
| 130 | + final_css.append(value.token) |
| 131 | + |
| 132 | + # for conditionals |
| 133 | + for attr, expression in self.css_dict.items(): |
| 134 | + real_value = expression.resolve(context) |
| 135 | + if real_value: |
| 136 | + final_css.append(attr) |
| 137 | + |
| 138 | + return " ".join(final_css) |
0 commit comments