From b256d12feebe934141e94cb4a9c4acfc3dbdecc2 Mon Sep 17 00:00:00 2001 From: Johannes Schriewer Date: Mon, 6 Jan 2025 03:16:33 +0100 Subject: [PATCH] New template tag: hilight which hilights a set of tokens with em tags --- inventory/templatetags/hilight.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 inventory/templatetags/hilight.py diff --git a/inventory/templatetags/hilight.py b/inventory/templatetags/hilight.py new file mode 100644 index 0000000..f6fa5cf --- /dev/null +++ b/inventory/templatetags/hilight.py @@ -0,0 +1,24 @@ +from django import template +from django.utils.safestring import mark_safe +from re import finditer + +register = template.Library() + + +@register.filter(name='hilight') +def hilight(text, tokens): + text = str(text) + for token in tokens: + ltext = text.lower() + for token in tokens: + positions = [] + for pos in finditer(token, ltext): + positions.append(pos.start()) + if len(positions) > 0: + offset = 0 + for pos in positions: + start = pos + offset + end = start + len(token) + text = text[:start] + f"{text[start:end]}" + text[end:] + offset += 9 + return mark_safe(text)