~cypheon/trakka

ref: e30fe514a2dd8f4e81d8cf3910e604f8faffa1a0 trakka/trakka/jinja2.py -rw-r--r-- 1.4 KiB
e30fe514 — Johann Rudloff Take climbed meters into account when estimating energy expenditure 1 year, 2 months ago
                                                                                
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
import datetime as dt

from django.templatetags.static import static
from django.urls import reverse

from jinja2 import Environment

from typing import Any, Optional

GLOBAL_STYLES = {
    'action-button': 'db ba b--black white f5 bg-dark-blue bold pa1 ph3 pointer hover-bg-blue bg-animate',
}

def duration(seconds: Optional[float]):
    if seconds is None:
        return '-'

    secs = int(seconds % 60)
    mins = int((seconds // 60) % 60)
    hours = int(seconds // 3600)

    if hours > 0:
        return f'{hours:d}:{mins:02d}:{secs:02d}'
    else:
        return f'{mins:d}:{secs:02d}'

def distance(meters: Optional[float]):
    if meters is None:
        return '-'
    return f'{meters/1000:0.1f} km'

def date(d: Optional[dt.datetime]) -> str:
    if d is None:
        return '-'
    return d.strftime('%d.\u202f%m.\u202f%Y')

def datetime(d: Optional[dt.datetime]) -> str:
    if d is None:
        return '-'
    return d.strftime('%d.\u202f%m.\u202f%Y\u202f%H:%M')

def optional_int(x: Optional[Any]) -> str:
    if x is None:
        return '-'
    return str(round(x))

def environment(**options):
    env = Environment(**options)
    env.globals.update({
        'static': static,
        'url': reverse,
        'styles': GLOBAL_STYLES,
    })
    env.filters.update({
        'date': date,
        'datetime': datetime,
        'distance': distance,
        'duration': duration,
        'optional_int': optional_int,
    })
    return env