from collections import namedtuple from json import loads as from_json from pathlib import Path from unicodedata import normalize ''' This plugin helps loading images for each section. Images should be located at /// eg. static/image/section1/folder-for-my-image/ static/image/section2/subsection/folder-for-another-image/ ... Each image folder should contain a file named `_metadata.json` with the following information { "name": "", "year": "", "category": "", "images": ["", "", "", ...] } Along with the image files which should be called ... ''' IMAGE_PATH = 'image' # relative to the static path STATIC = '' Image = namedtuple('Image', ['key', 'name', 'year', 'category', 'description', 'main', 'filenames']) # Functions def images(section): sec_path = Path(STATIC, IMAGE_PATH, section) for path in sec_path.iterdir(): if path.name.startswith('_'): continue metafile = path.joinpath('_metadata.json') if metafile.exists(): img_base = path.relative_to(STATIC) metadata = from_json(metafile.read_text()) key = path.name.split()[0] key = int(key) if key.isnumeric() else 0 img = Image( # key should always be the first field to sort images key, metadata.get('name'), metadata.get('year'), metadata.get('category'), metadata.get('description'), img_base.joinpath(normalize('NFC', metadata.get('main'))) if 'main' in metadata else None, [img_base.joinpath(normalize('NFC', img_name)) for img_name in metadata.get('images', [])]) yield img def init_plugin(env, config): global STATIC # update var STATIC STATIC = config['STATIC'] functions = [ images, sorted, map, str, list ] for f in functions: env.globals[f.__name__] = f