forked from rr326/waboardsailing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_jinja_filters.py
62 lines (51 loc) · 1.48 KB
/
custom_jinja_filters.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
Custom jinja filters
"""
import random
from collections.abc import Sequence
from typing import List, TypeVar
import markdown as markdown_library
T = TypeVar("T")
def split(value, sep, maxsplit=-1, strip=False) -> List | None:
"""
Same usage as str.split() as a jinja filter
strip == True - also strip each returned el
"""
if not isinstance(value, str):
return None
parts = value.split(sep, maxsplit)
return [el.strip() if isinstance(el, str) and strip else el for el in parts]
def el(value: T, idx: int) -> T: # pylint: disable=invalid-name
"""
If T = List, returns value[idx]
else: None
"""
if not isinstance(value, Sequence):
return None
return value[idx]
def shuffle(value: List) -> List:
"""
Returns a shuffled version of value
"""
if not isinstance(value, List):
return value
copied = value.copy()
random.shuffle(copied)
return copied
def markdown(value: str, skip_nomarkdown=True) -> str:
"""
Translates value (as markdown) into html
skip_nomarkdown: if True, and text has no markdown, don't wrap in p.
ex: "text" --> "<p>text</p>" --> "text"
"""
if not isinstance(value, str):
return value
try:
html = markdown_library.markdown(value)
if skip_nomarkdown:
if html == "<p>"+value+"</p>":
html = value
except Exception as err:
return f"Markdown Error ({err}) on {value}"
else:
return html