|
| 1 | +import os |
| 2 | +import shutil |
| 3 | +from jinja2 import Environment, FileSystemLoader |
| 4 | + |
| 5 | +# Configuration |
| 6 | +TEMPLATE_DIR = "templates" |
| 7 | +STATIC_DIR = "static" |
| 8 | +OUTPUT_DIR = "_site" |
| 9 | + |
| 10 | + |
| 11 | +def build_static_site(): |
| 12 | + """Builds the static site from Jinja2 templates.""" |
| 13 | + print("Starting Static Site Build...") |
| 14 | + |
| 15 | + # 1. Prepare Output Directory |
| 16 | + if os.path.exists(OUTPUT_DIR): |
| 17 | + shutil.rmtree(OUTPUT_DIR) |
| 18 | + os.makedirs(OUTPUT_DIR) |
| 19 | + print(f"Created output directory: {OUTPUT_DIR}") |
| 20 | + |
| 21 | + # 2. Copy Static Assets |
| 22 | + # Copy contents of 'static' folder to '_site' root (so css/style.css works as expected) |
| 23 | + # The template expects 'css/' and 'js/' to be at the root relative to the HTML file |
| 24 | + |
| 25 | + # Copy individual subdirectories to maintain structure |
| 26 | + if os.path.exists(STATIC_DIR): |
| 27 | + for item in os.listdir(STATIC_DIR): |
| 28 | + s = os.path.join(STATIC_DIR, item) |
| 29 | + d = os.path.join(OUTPUT_DIR, item) |
| 30 | + if os.path.isdir(s): |
| 31 | + shutil.copytree(s, d) |
| 32 | + else: |
| 33 | + shutil.copy2(s, d) |
| 34 | + print(f"Copied static assets from {STATIC_DIR} to {OUTPUT_DIR}") |
| 35 | + else: |
| 36 | + print(f"Warning: Static directory '{STATIC_DIR}' not found.") |
| 37 | + |
| 38 | + # 3. Render Templates |
| 39 | + env = Environment(loader=FileSystemLoader(TEMPLATE_DIR)) |
| 40 | + |
| 41 | + # List of pages to render |
| 42 | + pages = [ |
| 43 | + {"template": "index.html", "output": "index.html"}, |
| 44 | + {"template": "history.html", "output": "history.html"}, |
| 45 | + {"template": "help.html", "output": "help.html"}, |
| 46 | + ] |
| 47 | + |
| 48 | + for page in pages: |
| 49 | + try: |
| 50 | + template = env.get_template(page["template"]) |
| 51 | + output_content = template.render(request=None, is_static=True) |
| 52 | + |
| 53 | + output_path = os.path.join(OUTPUT_DIR, page["output"]) |
| 54 | + with open(output_path, "w", encoding="utf-8") as f: |
| 55 | + f.write(output_content) |
| 56 | + |
| 57 | + print(f"Rendered: {page['template']} -> {page['output']}") |
| 58 | + except Exception as e: |
| 59 | + print(f"Error rendering {page['template']}: {e}") |
| 60 | + |
| 61 | + print("Build Complete!") |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + build_static_site() |
0 commit comments