alucho_images.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from collections import namedtuple
  2. from json import loads as from_json
  3. from pathlib import Path
  4. '''
  5. This plugin helps loading images for each section.
  6. Images should be located at
  7. <static-folder>/<image-path>/<section-name>/<image-folder>
  8. eg.
  9. static/image/section1/folder-for-my-image/
  10. static/image/section2/subsection/folder-for-another-image/
  11. ...
  12. Each image folder should contain a file named `_metadata.json`
  13. with the following information
  14. {
  15. "name": "<image-name>",
  16. "year": "<year>",
  17. "category": "<category-name>",
  18. "images": ["<main-image-name>", "<image-variant-1>", "<image-variant-2>", ...]
  19. }
  20. Along with the image files which should be called
  21. <main-image-name>
  22. <image-variant-1>
  23. <image-variant-2>
  24. ...
  25. '''
  26. IMAGE_PATH = 'image' # relative to the static path
  27. STATIC = ''
  28. Image = namedtuple('Image', ['name', 'year', 'category', 'description', 'filenames'])
  29. # Functions
  30. def images(section):
  31. sec_path = Path(STATIC, IMAGE_PATH, section)
  32. for path in sec_path.iterdir():
  33. if path.name.startswith('_'):
  34. continue
  35. metafile = path.joinpath('_metadata.json')
  36. if metafile.exists():
  37. img_base = path.relative_to(STATIC)
  38. metadata = from_json(metafile.read_text())
  39. img = Image(
  40. metadata.get('name'),
  41. metadata.get('year'),
  42. metadata.get('category'),
  43. metadata.get('description'),
  44. [img_base.joinpath(img_name) for img_name in metadata.get('images', [])])
  45. print(img)
  46. yield img
  47. def init_plugin(env, config):
  48. global STATIC
  49. STATIC = config['STATIC']
  50. env.globals['images'] = images