from article import Article, Site from dataclasses import dataclass from io import TextIOWrapper from jinja2 import Environment, Template, FileSystemLoader, select_autoescape from json import loads from os.path import join TEMPLATE_VERSIONS = [1] @dataclass class TemplateConfig: version: int name: str articles_per_page: int @staticmethod def from_open_file(file: TextIOWrapper) -> "TemplateConfig": content = file.read() data = loads(content) if data['version'] not in TEMPLATE_VERSIONS: raise ValueError('Template version' + data['version'] + ' is not compatible. ' + # TODO right exception? 'Supported versions: ' + ', '.join(str(i) for i in TEMPLATE_VERSIONS)) return TemplateConfig(**data) class TemplateEnvironment: environment: Environment config: TemplateConfig site: Site article_template: Template index_template: Template def __init__(self, template_directory: str, site: Site): self.environment = Environment( loader = FileSystemLoader(template_directory, followlinks=True), autoescape = select_autoescape() ) self.site = site self.article_template = self.environment.get_template('article_template.html') self.index_template = self.environment.get_template('index.html') self.__load_config(template_directory) def __load_config(self, template_directory: str): fn = join(template_directory, 'template.json') file = open(fn) self.config = TemplateConfig.from_open_file(file) file.close() def process_article(self, article: Article) -> str: return self.article_template.render( site = self.site, article = article ) def process_index(self, *articles: Article) -> str: return self.index_template.render( site = self.site, articles = articles )