page.py 1.57 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import uuid
import re
import yaml


class Page:
    def __init__(self, slug, page_content, configuration={}):
        # We initialize the page meta variables which will be accessible in the
        # template
        self.meta = {}
        self.meta.update(configuration)
        self.meta["PAGE_SLUG"] = slug
        self.meta["PAGE_TEMPLATE"] = "page"
        yaml_conf, page_content = extract_yaml_configuration(page_content)
        for key, value in yaml_conf.items():
            article_key = f"PAGE_{key.upper()}"
            self.meta[article_key] = value
        self.meta["PAGE_CONTENT"] = page_content

    def slug(self):
        return self.meta["PAGE_SLUG"]

    def title(self):
        return self.meta.get("PAGE_TITLE", "A page")

    def url(self):
        site_url = self.meta.get("SITE_URL", "")
        return f"{site_url}{self.slug()}.html"

    def uuid(self):
        return str(uuid.uuid5(uuid.NAMESPACE_URL, self.url()))

    def content(self):
        return self.meta["PAGE_CONTENT"]

36
37
38
    def template(self):
        return self.meta["PAGE_TEMPLATE"]

39
40
41
42
43
44
45
    def set_articles(self, articles):
        articles.sort(key=lambda article: article.date(), reverse=False)
        self.meta["ARTICLES"] = articles

    def set_feed(self, feed):
        self.meta["FEED"] = feed

46
47
48
49
50
51
52
53
54
55
56

YAML_FRONT_MATTER_REGEX = re.compile("(---\n.*\n)(---\n)(.*)", re.M | re.S)


def extract_yaml_configuration(content):
    match = YAML_FRONT_MATTER_REGEX.match(content)
    if match:
        yaml_conf = yaml.load(match.group(1))
        return yaml_conf, match.group(3)
    else:
        return {}, content