Use decorators in jinja_filters to automatically register them.

master
voussoir 2020-09-09 13:23:16 -07:00
parent 199a4af658
commit c425d55331
2 changed files with 27 additions and 8 deletions

View File

@ -32,14 +32,7 @@ site.config.update(
site.jinja_env.add_extension('jinja2.ext.do')
site.jinja_env.trim_blocks = True
site.jinja_env.lstrip_blocks = True
site.jinja_env.filters['bytestring'] = jinja_filters.bytestring
site.jinja_env.filters['comma_join'] = jinja_filters.comma_join
site.jinja_env.filters['file_link'] = jinja_filters.file_link
site.jinja_env.filters['sort_tags'] = jinja_filters.sort_tags
site.jinja_env.filters['timestamp_to_8601'] = jinja_filters.timestamp_to_8601
site.jinja_env.filters['timestamp_to_naturaldate'] = jinja_filters.timestamp_to_naturaldate
site.jinja_env.filters['users_to_usernames'] = jinja_filters.users_to_usernames
site.jinja_env.globals['make_attributes'] = jinja_filters.make_attributes
jinja_filters.register_all(site)
site.debug = True
P = etiquette.photodb.PhotoDB()

View File

@ -3,24 +3,45 @@ import jinja2.filters
import voussoirkit.bytestring
filter_functions = []
global_functions = []
def filter_function(function):
filter_functions.append(function)
return function
def global_function(function):
global_functions.append(function)
return function
def register_all(site):
for function in filter_functions:
site.jinja_env.filters[function.__name__] = function
for function in global_functions:
site.jinja_env.globals[function.__name__] = function
@filter_function
def bytestring(x):
try:
return voussoirkit.bytestring.bytestring(x)
except Exception as e:
return '??? b'
@filter_function
def comma_join(l):
if not l:
return ''
return ', '.join(l)
@filter_function
def file_link(photo, short=False):
if short:
return f'/file/{photo.id}{photo.dot_extension}'
basename = jinja2.filters.do_urlencode(photo.basename)
return f'/file/{photo.id}/{basename}'
@global_function
def make_attributes(*booleans, **keyvalues):
keyvalues = {key: value for (key, value) in keyvalues.items() if value is not None}
attributes = [f'{key}="{jinja2.filters.escape(value)}"' for (key, value) in keyvalues.items()]
@ -28,20 +49,25 @@ def make_attributes(*booleans, **keyvalues):
attributes = ' '.join(attributes)
return attributes
@filter_function
def sort_tags(tags):
tags = sorted(tags, key=lambda x: x.name)
return tags
@filter_function
def timestamp_to_8601(timestamp):
return datetime.datetime.utcfromtimestamp(timestamp).isoformat(' ') + ' UTC'
@filter_function
def timestamp_to_string(timestamp, format):
date = datetime.datetime.utcfromtimestamp(timestamp)
return date.strftime(format)
@filter_function
def timestamp_to_naturaldate(timestamp):
return timestamp_to_string(timestamp, '%B %d, %Y')
@filter_function
def users_to_usernames(users):
if not users:
return []