Super simple static site generator
I thought static site generators seemed like a cool modern alternative to frames until I looked at how they worked. Utter insanity. I'd rather learn php. If your site uses frames and/or could be easily rewritten to, this is the static site generator for you.
This works in Python 2.7 and Python 3. I could just about say I "wrote" it, because I transcribed it as my husband dictated it. I actually understood enough to spot a mistake, so let's just go ahead and say I wrote it all myself.
This is how I have my files and folders set up:
/website /_building /pages builder.py footer.html header.html
/pages, footer.html and header.html are part of the script and need to be changed there if you change them. Everything else you can name whatever you want. I use an underscore at the start of this working folder name to keep it separate from my real for-upload folders. The files in the /pages folder should have their final intended names, ie index.html, about.html
It outputs into the /website folder, whatever it's called. It works with subfolders, too (like my /articles subfolder), but pay attention to the links/image paths/stylesheet locations/etc. in your header and footer (they need to start with a slash if you use subfolders)
import os
file_list = os.listdir("pages")
for file in file_list[:]:
if os.path.isdir(os.path.join("pages", file)):
for subfile in os.listdir(os.path.join("pages", file)):
file_list.append(os.path.join(file, subfile))
with open("header.html", "r") as f:
header = f.read()
with open("footer.html", "r") as f:
footer = f.read()
for file in file_list:
if os.path.isdir(os.path.join("pages", file)):
try:
os.makedirs(os.path.join("..", file))
except:
pass
continue
print (file)
with open(os.path.join("pages", file), "r") as f:
contents = f.read()
contents = header + contents + footer
with open(os.path.join("..", file), "w") as f:
f.write(contents)
This version only builds the page if you've created a new page, edited a page, or edited the header/footer:
import os
file_list = os.listdir("pages")
for file in file_list[:]:
if os.path.isdir(os.path.join("pages", file)):
for subfile in os.listdir(os.path.join("pages", file)):
file_list.append(os.path.join(file, subfile))
with open("header.html", "r") as f:
header = f.read()
header_edittime = os.path.getmtime("header.html")
with open("footer.html", "r") as f:
footer = f.read()
footer_edittime = os.path.getmtime("footer.html")
for file in file_list:
if (
os.path.exists(os.path.join("..", file))
and
max(
os.path.getmtime(os.path.join("pages", file)),
header_edittime,
footer_edittime,
)< os.path.getmtime(os.path.join("..", file))
):
continue
if os.path.isdir(os.path.join("pages", file)):
try:
os.makedirs(os.path.join("..", file))
except:
pass
continue
print (file)
with open(os.path.join("pages", file), "r") as f:
contents = f.read()
contents = header + contents + footer
with open(os.path.join("..", file), "w") as f:
f.write(contents)