Skip to content

Commit a556150

Browse files
committed
Add dyamic duration formatting
1 parent c5972d2 commit a556150

File tree

4 files changed

+44
-1
lines changed

4 files changed

+44
-1
lines changed

cal.py

+4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import config
66
import views
7+
from filters import filters
78
from models import db, login_manager
89

910
app = Flask(__name__, static_url_path='')
@@ -19,3 +20,6 @@
1920

2021
app.jinja_env.trim_blocks = True
2122
app.jinja_env.lstrip_blocks = True
23+
24+
for name, func in filters.items():
25+
app.add_template_filter(func, name=name)

constants.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from collections import OrderedDict
2+
3+
SECOND = 1
4+
MINUTE = 60 * SECOND
5+
HOUR = 60 * MINUTE
6+
DAY = 24 * HOUR
7+
WEEK = 7 * DAY
8+
9+
TIME_UNITS = OrderedDict([
10+
('second', SECOND),
11+
('minute', MINUTE),
12+
('hour', HOUR),
13+
('day', DAY),
14+
('week', WEEK),
15+
])
16+
17+
TIME_ABBREVIATIONS = OrderedDict([
18+
('second', 's'),
19+
('minute', 'm'),
20+
('hour', 'h'),
21+
('day', 'd'),
22+
('week', 'w'),
23+
])

filters.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import constants
2+
3+
4+
def formatted_duration(duration, input='hour'):
5+
base_duration = float(duration * constants.TIME_UNITS[input])
6+
parts = []
7+
for unit, value in constants.TIME_UNITS.items()[::-1]:
8+
if base_duration >= value:
9+
parts.append((base_duration / value, constants.TIME_ABBREVIATIONS[unit]))
10+
base_duration %= value
11+
return ' '.join('%d %s' % (value, abbr) for value, abbr in parts)
12+
13+
14+
filters = {
15+
'duration': formatted_duration,
16+
}

templates/events/list.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
<td><a href="{{ url_for('events.events_detail', event_id=event.id) }}">{{ event.title }}</a></td>
4545
<td>{{ event.description }}</td>
4646
<td><time class="timeago" datetime="{{ event.start_time_format }}">{{ event.start_time_format }}</time></td>
47-
<td>{{ event.duration / 24 }} days</td>
47+
<td>{{ event.duration|duration }}</td>
4848
<td><a href="{{ event.link }}" target="_blank">Website</a></td>
4949
{% if enabled_actions %}
5050
<td>

0 commit comments

Comments
 (0)