-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate.py
More file actions
166 lines (134 loc) Β· 5.04 KB
/
generate.py
File metadata and controls
166 lines (134 loc) Β· 5.04 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#!/usr/bin/env python3
"""
HTML Generator for Community Pages
This script generates HTML pages from JSON data using Jinja2 templates.
It supports multiple pages, each with their own folder containing content.json,
style.css, script.js, and generates body.html with inline CSS/JS.
"""
import json
import os
import sys
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
def load_data(page_folder):
"""Load content data from JSON file in page folder."""
content_file = Path(page_folder) / "content.json"
if not content_file.exists():
raise FileNotFoundError(f"content.json not found in {page_folder}")
with open(content_file, 'r', encoding='utf-8') as f:
return json.load(f)
def load_css_content(page_folder):
"""Load CSS content from style.css in page folder."""
css_file = Path(page_folder) / "style.css"
if not css_file.exists():
raise FileNotFoundError(f"style.css not found in {page_folder}")
with open(css_file, 'r', encoding='utf-8') as f:
return f.read()
def load_js_content(page_folder):
"""Load JavaScript content from script.js in page folder."""
js_file = Path(page_folder) / "script.js"
if not js_file.exists():
raise FileNotFoundError(f"script.js not found in {page_folder}")
with open(js_file, 'r', encoding='utf-8') as f:
return f.read()
def setup_jinja_env(template_dir="templates"):
"""Setup Jinja2 environment with template directory."""
return Environment(
loader=FileSystemLoader(template_dir),
autoescape=True
)
def generate_page_html(page_name, page_folder):
"""Generate HTML file for a specific page."""
print(f"π§ Generating {page_name} page...")
# Load data and assets
try:
data = load_data(page_folder)
css_content = load_css_content(page_folder)
js_content = load_js_content(page_folder)
except FileNotFoundError as e:
print(f"β Error: {e}")
return False
# Setup Jinja2 environment
env = setup_jinja_env()
# Load page-specific template (fallback to base.html if not found)
try:
template = env.get_template(f'{page_name}/index.html')
except Exception:
try:
template = env.get_template('base.html')
except Exception as e:
print(f"β Error loading template: {e}")
return False
# Prepare template data
template_data = {
**data,
'page_name': page_name,
'css_content': css_content,
'js_content': js_content
}
# Render template with data
try:
html_content = template.render(**template_data)
except Exception as e:
print(f"β Error rendering template: {e}")
return False
# Write HTML file
output_file = Path(page_folder) / "body.html"
try:
with open(output_file, 'w', encoding='utf-8') as f:
f.write(html_content)
print(f"β
Generated: {output_file}")
return True
except Exception as e:
print(f"β Error writing HTML file: {e}")
return False
def find_page_folders():
"""Find all page folders (directories containing content.json)."""
page_folders = []
current_dir = Path('.')
for item in current_dir.iterdir():
if item.is_dir() and (item / "content.json").exists():
page_folders.append(item.name)
return sorted(page_folders)
def generate_all_pages():
"""Generate HTML for all discovered page folders."""
page_folders = find_page_folders()
if not page_folders:
print("β No page folders found. Each page should have a folder with content.json")
return False
print(f"π Found page folders: {', '.join(page_folders)}")
success_count = 0
for page_name in page_folders:
if generate_page_html(page_name, page_name):
success_count += 1
print(f"β¨ Generated {success_count}/{len(page_folders)} pages successfully!")
return success_count == len(page_folders)
def generate_specific_page(page_name):
"""Generate HTML for a specific page."""
page_folder = Path(page_name)
if not page_folder.exists():
print(f"β Page folder '{page_name}' not found")
return False
if not (page_folder / "content.json").exists():
print(f"β content.json not found in '{page_name}' folder")
return False
return generate_page_html(page_name, page_folder)
def main():
"""Main function to generate HTML pages."""
print("π Community Page Generator")
print("=" * 50)
# Check command line arguments
if len(sys.argv) > 1:
page_name = sys.argv[1]
print(f"Generating specific page: {page_name}")
success = generate_specific_page(page_name)
else:
print("Generating all pages...")
success = generate_all_pages()
if success:
print("\nπ Generation completed successfully!")
else:
print("\nπ₯ Generation failed!")
sys.exit(1)
if __name__ == "__main__":
main()