By using this site, you agree to have cookies stored on your device, strictly for functional purposes, such as storing your session and preferences.

Dismiss

 extra_jinja.py

View raw Download
text/x-script.python • 7.35 kiB
Python script, Unicode text, UTF-8 text executable
        
            
1
import math
2
import datetime
3
import re
4
5
def init_filters(site):
6
@site.filter("first_paragraph")
7
def first_paragraph(value):
8
return value.split("\n\n")[0]
9
@site.filter("split")
10
def split(value, sep, maxsplit=-1):
11
return value.split(sep, maxsplit)
12
@site.filter("rsplit")
13
def rsplit(value, sep, maxsplit=-1):
14
return value.rsplit(sep, maxsplit)
15
@site.filter("splitlines")
16
def splitlines(value, keepends=False):
17
return value.splitlines(keepends)
18
@site.filter("split_any")
19
def split_any(value, separators, maxsplit=-1):
20
return re.split("|".join(re.escape(sep) for sep in separators), value, maxsplit)
21
@site.filter("split_regex")
22
def split_regex(value, pattern, maxsplit=-1):
23
return re.split(pattern, value, maxsplit)
24
@site.filter("partition")
25
def partition(value, sep):
26
return value.partition(sep)
27
@site.filter("rpartition")
28
def rpartition(value, sep):
29
return value.rpartition(sep)
30
@site.filter("lstrip")
31
def lstrip(value, chars=None):
32
return value.lstrip(chars)
33
@site.filter("rstrip")
34
def rstrip(value, chars=None):
35
return value.rstrip(chars)
36
@site.filter("strip")
37
def strip(value, chars=None):
38
return value.strip(chars)
39
@site.filter("removeprefix")
40
def removeprefix(value, prefix):
41
return value.removeprefix(prefix)
42
@site.filter("removesuffix")
43
def removesuffix(value, suffix):
44
return value.removesuffix(suffix)
45
@site.filter("remove")
46
def remove(value, string):
47
return value.replace(string, "")
48
@site.filter("strftime")
49
def strftime(value: datetime.datetime | datetime.date | datetime.time, format_):
50
return value.strftime(format_)
51
@site.filter("unixtime")
52
def unixtime(value: datetime.datetime | datetime.date | datetime.time):
53
return round(value.timestamp())
54
@site.filter("strptime")
55
def strptime(value, format_):
56
return datetime.datetime.strptime(value, format_)
57
@site.filter("round")
58
def round_(value, decimals=0):
59
return round(value, decimals)
60
@site.filter("floor")
61
def floor(value):
62
return math.floor(value)
63
@site.filter("ceiling")
64
def ceiling(value):
65
return math.ceil(value)
66
@site.filter("units")
67
def units(value, decimals=2, scale=1024,
68
suffixes=("B", "kiB", "MiB", "GiB", "TiB", "PiB")):
69
for unit in suffixes:
70
if value < scale:
71
break
72
value /= scale
73
if int(value) == value:
74
return int(value) + "\u202f" + unit
75
return round(value * 10 ** decimals) / 10 ** decimals + "\u202f" + unit
76
@site.filter("conditional")
77
def conditional(value, true_value, false_value):
78
return true_value if value else false_value
79
@site.filter("debug_log_value")
80
def debug_log_value(value):
81
print(value)
82
return value
83
@site.filter("harvester_protection")
84
def harvester_protection(value):
85
return "".join(f"&#x{ord(char):x};" for char in value)
86
@site.filter("pretty_number")
87
def pretty_number(value, separator="\u202f"):
88
return f"{value:,}".replace(",", separator)
89
@site.filter("hex")
90
def hex_(value):
91
return hex(value).removeprefix("0x")
92
@site.filter("oct")
93
def oct_(value):
94
return oct(value).removeprefix("0o")
95
@site.filter("bin")
96
def bin_(value):
97
return bin(value).removeprefix("0b")
98
@site.filter("join")
99
def join(value, separator=" "):
100
return separator.join(value)
101
@site.filter("replace")
102
def replace(value, old, new):
103
return value.replace(old, new)
104
@site.filter("file_stat")
105
def file_stat(value):
106
return value.stat()
107
@site.filter("path_cat")
108
def path_cat(*value):
109
return os.path.join(*value)
110
@site.filter("path_dirname")
111
def path_dirname(value):
112
return os.path.dirname(value)
113
@site.filter("path_basename")
114
def path_basename(value):
115
return os.path.basename(value)
116
@site.filter("path_splitext")
117
def path_splitext(value):
118
return os.path.splitext(value)
119
@site.filter("type")
120
def type_(value):
121
return type(value)
122
@site.filter("type_name")
123
def type_name(value):
124
return type(value).__name__
125
@site.filter("each_nth")
126
def nth(value, step, start=0):
127
return value[start::step]
128
@site.filter("key_list")
129
def key_list(value):
130
return list(value.keys())
131
@site.filter("value_list")
132
def value_list(value):
133
return list(value.values())
134
@site.filter("item_list")
135
def item_list(value):
136
return list(value.items())
137
@site.filter("remove_dupes")
138
def remove_dupes(value):
139
list = []
140
for i in value:
141
if i not in list:
142
list.append(i)
143
return list
144
@site.filter("percent")
145
def percent(value, maximum, decimals=2):
146
return round(value * maximum / 100, decimals) + "%"
147
@site.filter("percent_of")
148
def percent_of(value, total, decimals=2):
149
return round(value / total * 100, decimals) + "%"
150
@site.filter("permille")
151
def permille(value, maximum, decimals=2):
152
return round(value * maximum / 1000, decimals) + "‰"
153
@site.filter("permille_of")
154
def permille_of(value, total, decimals=2):
155
return round(value / total * 1000, decimals) + "‰"
156
@site.filter("timezone")
157
def timezone(value, timezone):
158
return value.astimezone(timezone)
159
160
def init_tests(site):
161
@site.test("instance_of")
162
def isinstance_(value, type_):
163
return isinstance(value, type_)
164
@site.test("only_chars")
165
def only_chars(value, chars):
166
return set(value).issubset(set(chars))
167
@site.test("empty")
168
def is_empty(value):
169
return not len(value)
170
@site.test("not_empty")
171
def is_not_empty(value):
172
return len(value)
173
@site.test("past_date")
174
def past_date(value):
175
return value < datetime.datetime.now()
176
@site.test("future_date")
177
def future_date(value):
178
return value > datetime.datetime.now()
179
@site.test("numeric")
180
def is_numeric(value):
181
try:
182
float(value)
183
return True
184
except ValueError:
185
return False
186
@site.test("startswith")
187
def startswith(value, prefix):
188
return value.startswith(prefix)
189
@site.test("endswith")
190
def endswith(value, suffix):
191
return value.endswith(suffix)
192
@site.test("matches_regex")
193
def matches_regex(value, pattern):
194
return re.match(pattern, value) is not None
195
@site.test("is_callable")
196
def is_callable(value):
197
return callable(value)
198
@site.test("all")
199
def all_(value):
200
return all(value)
201
@site.test("any")
202
def any_(value):
203
return any(value)
204
@site.test("longer_than")
205
def longer_than(value, length):
206
return len(value) > length
207
@site.test("shorter_than")
208
def shorter_than(value, length):
209
return len(value) < length
210
@site.test("weekend")
211
def weekend(value):
212
return value.weekday() >= 5
213
@site.test("weekday")
214
def weekday(value):
215
return value.weekday() < 5
216
@site.test("leap_year")
217
def leap_year(value):
218
return value.year % 4 == 0 and (value.year % 100 != 0 or value.year % 400 == 0)
219
@site.test("almost_equal")
220
def almost_equal(value, other, tolerance=1e-6):
221
return abs(value - other) < tolerance
222