My site generator is a simple thing. It's not
meant to generate a whole website, but rather
generate the last few posts, which I then move
manually to the desired folder. That's enough
for my little thing and gives me a chance to
revise the changed elements.
That's what I do.
I'm using a simple jinja2 template such as:
{{ y['title'] }}
... some more code...
Did you notice the {{ y['title'] }} thing?
Double curly braces and all?
The script will change that for whatever is in the
y['title'] variable.
And where's that script?
Well, in a separate file called whatever.py
Yeah, it's in python, though it could be in a ton
of different programming languages.
(Pros, bear with me, I'm writing so a
random 12 y/o with any skill can do something
with it)
Anyway, here it is!
-=-=-=-=-=-=-=-=-=
from jinja2 import (Environment, PackageLoader,
select_autoescape, FileSystemLoader)
from entries import entries
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template("layout.html")
for entry in entries:
to_write = template.render(y=entry)
with open("out/" + entry["filename"]+".html", "w") as tf:
tf.write(to_write)
First line, it just imports some modules (aka code
that we can re-use)
"from entries import entries" I have the entries
on a separate file (in the same folder to keep
things simple). We import it now :)
"env = ..." just tells Python the folder (aka directory)
where I saved the templates
"template = ..." just loads the file "layout.html",
on the folder 'templates' as I told Python on the
previous line
Now we have a little loop. Literally it goes for
each entry in the entries "object" we imported earlier.
(I'll show it soon enough!)
For each entry...
First it tells python to use those nice jinja2 module
some great generous programmers created and mantained
and render it for us. See that y=entry ? I'm just
loading the contents of entry into a variable called
y, so to keep the layout cleaner.
Finally, the bit that starts with... :) "With", is
just an standard python way to create and save a
file. Check the docs.
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
That's almost all...
Let's see the object file, called, surprise entries.py
# -*- coding: utf-8 -*-
entries = [
{
"filename" = "first",
"title" = "First entry",
"content" = """
Something
This is just an example. Notice, I'm
using triple quotes, so the text can
span multiple lines and python won't
freak out about it.
"""
},
{
"filename" = "second",
"title" = "Second entry",
"content" = """
Something else
This is example is more minimal
than my actual system. It all depends
on how many "things" you want to vary
in your blog posts / documents / whatever
text you want to generate.
"""
},
]
Well, that's actually a list of small
objects. Notice the commas, don't miss
one, read the error messages. (Error
messages are your friends), and do read
the docs. You can do anything if you
read the docs.
2025-04-27 16:00:59