Skip to content

Instantly share code, notes, and snippets.

@Kraballa
Created September 5, 2024 16:30
Show Gist options
  • Save Kraballa/4123682890835f6899ff53c522eb0aab to your computer and use it in GitHub Desktop.
Save Kraballa/4123682890835f6899ff53c522eb0aab to your computer and use it in GitHub Desktop.
jinja2 static website template renderer
import shutil
import os
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('.'))
def renderFile(filename):
origPath = "files/" + filename
newPath = "output/" + filename
template = env.get_template(origPath)
output = template.render()
with open(newPath, "wb") as fh:
fh.write(output.encode('utf-8'))
pass
if __name__ == "__main__":
# copy all files from verbatim folder to output
shutil.copytree("./verbatim", "./output", dirs_exist_ok=True)
for subdir, dirs, files in os.walk("files"):
for file in files:
if file.endswith(".html"):
print("rendering", file)
renderFile(file)
@Kraballa
Copy link
Author

Kraballa commented Sep 5, 2024

Usage

The script is concerned with the following folders on the same directory:

  • the output folder is where the final result is copied to
  • the contents of the verbatim folder is copied 1:1 to output
  • all .html files in the files folder gets rendered with jinja and copied to output

Personally in the main directory I have a template and then each html file in files simply extends it. This saves me (and you) from needlessly having to copy header, footer and scripts into every single subpage, keeping it all DRY. Static website with template rendering made easy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment