Created
September 5, 2024 16:30
-
-
Save Kraballa/4123682890835f6899ff53c522eb0aab to your computer and use it in GitHub Desktop.
jinja2 static website template renderer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
The script is concerned with the following folders on the same directory:
output
folder is where the final result is copied toverbatim
folder is copied 1:1 tooutput
.html
files in thefiles
folder gets rendered with jinja and copied tooutput
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!