diff --git a/aleksis/core/templatetags/html_helpers.py b/aleksis/core/templatetags/html_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..2601b3aad97453ce761e02d86a6443260ceab473 --- /dev/null +++ b/aleksis/core/templatetags/html_helpers.py @@ -0,0 +1,23 @@ +from typing import Any + +from django import template + +from bs4 import BeautifulSoup + +register = template.Library() + + +@register.filter +def add_class_to_el(value: str, arg: str) -> str: + """Add a CSS class to every occurence of an element type. + + Example: {{ mymodel.myhtmlfield|add_class_to_el:"ul,browser-default" + """ + + el, cls = value.split(",") + soup = BeautifulSoup(value, "html.parser") + + for el in soup.find_all(el): + el["class"] = el.get("class", "") + f" {cls}" + + return str(soup)