onpoint/helper.py

54 lines
2.1 KiB
Python
Executable File

import os
import stat
import yaml
import re
# Calls a YAML parser for the given relative path inside the presentation root
# directory. Returns a dictionary with the YAML content.
def read_yaml(root, path):
with open(os.path.join(root, path), 'r', encoding='utf8') as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
# Retrieve the available languages as stated in the meta.yml (key: language).
def get_available_languages(root):
return read_yaml(root, 'meta.yml')['language']
# Replaces the placeholders in the given content with corresponding values in
# the given language from the meta.yml and returns the filled content.
def insert_metadata(content, root, lang):
metadata = read_yaml(root, 'meta.yml')
for key, value in metadata.items():
placeholder = '@' + key
filler = value[lang]
# print('replace', placeholder, 'with', filler)
if '@' + key in content:
content = content.replace(placeholder, filler)
return content
# Retrieve the modification time for a given file.
def get_modification_time(path):
return os.stat(path)[stat.ST_MTIME]
# Replace the "src" attribute on images by "data-src".
# Should be done after caching because fragments#defragmentize requires
# valid XHTML and data-src causes problems with that.
# Also: Toggling lazyload is easier this way.
def add_lazyload(source, lazyload_images):
if lazyload_images:
return re.sub(r'<img(.*)src=', r'<img\1data-src=', source)
else:
return source
# Replace all occurrences of "@help" by the content specified
# in "help-menu.html". The "@help" annotation should be used only once
# per presentation.
def add_help_menu(source, root):
help_menu_code = open(os.path.join(
root, 'onpoint/help-menu.html'), 'r', encoding='utf8').read()
help_menu_code = re.sub('@imprint', read_yaml(root, 'legal.yml')['imprint'], help_menu_code)
help_menu_code = re.sub('@privacy-policy', read_yaml(root, 'legal.yml')['privacy-policy'], help_menu_code)
return re.sub('@help', help_menu_code, source)