python / intermediate
Snippet
Custom Template Filter Function for Processing List Items
Custom Django template filters are Python functions registered via `template.Library().filter`. This snippet demonstrates list comprehension and string manipulation within a filter function to dynamically highlight specific keywords in template strings.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
from django import templateregister = template.Library()@register.filter(name="highlight_keywords")def highlight_keywords(text: str, keywords_csv: str) -> str:if not text or not keywords_csv:return textkeywords = [kw.strip() for kw in keywords_csv.split(",") if kw.strip()]for kw in keywords:text = text.replace(kw, f"<strong>{kw}</strong>")return text
django
Breakdown
1
register = template.Library()
Instantiates the template library instance used to register custom tags and filters.
2
@register.filter(name="highlight_keywords")
Decorator registering the function as a template filter named highlight_keywords.
3
def highlight_keywords(text: str, keywords_csv: str) -> str:
Defines the filter function with type annotations for input text and arguments.
4
keywords = [kw.strip() for kw in keywords_csv.split(",") if kw.strip()]
Uses a list comprehension to split, trim, and filter out empty keyword tokens.
5
for kw in keywords:
Iterates through the cleaned keyword array to wrap matches in HTML tags.