snippets/generator.py

72 lines
1.8 KiB
Python

from os import walk
from os import path
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
@dataclass
class Article:
id: str # html id on page
category: str
title: str
path: str
description: Optional[str] = None
def read_contents(self) -> str:
return Path(self.path).read_text()
articles_by_category = {
"art": [
Article(
"art-001",
"art",
"How I Have Recently Commissioned (Furry) Art",
"./politecafe/input/art-001.html",
)
],
"cult": [
Article(
"cult-002",
"cult",
"How to Get High with Cannabis in 2024",
"./politecafe/input/cult-002.html",
)
],
"tech": [
Article(
"tech-001",
"tech",
"How To Enjoy Mastodon in 3 Steps",
"./politecafe/input/tech-001.html",
),
Article(
"tech-002",
"tech",
"How & Why To Use Dependency Injection With Python",
"./politecafe/input/tech-002.html",
),
],
}
# generate slugs and read articles
slugs = []
article_contents = []
for category, articles in articles_by_category.items():
for article in articles:
contents = article.read_contents()
article_contents.append(contents)
slug = f"""<p><a href="#{article.id}">{article.title}</a></p>"""
slugs.append(slug)
# plug into template, write to index.html
template = Path("./politecafe/input/template.html").read_text()
template = template.replace(
"<div><!--- Articles ---></div>", "\n".join(article_contents)
)
template = template.replace("<div><!--- Slugs ---></div>", "\n".join(slugs))
with open("./politecafe/index.html", "w", encoding="utf-8") as index_html:
index_html.write(template)