Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Use Python's Built-In Template Strings To Generate Output

Code

from string import Template

skeleton = """
The value is: $VALUE
"""

data = { "VALUE": "quick fox" }
template = Template(skeleton)
output = template.substitute(data)
print(output)

Results

The value is: quick fox

This is a basic one where you pass it two paths and a data dictionary and it makes the output.

Code

from string import Template

def make_page(template_path, output_path, data):
    with open(template_path) as _template:
        template = Template(_template.read())
        with open(output_path, 'w') as _output:
            _output.write(
                template.substitute(data)
            )

And here's a full boiler plate:

Code

from string import Template

def data_builder():
    data = {}
    data['CODE'] = 'this is here'
    return data

def make_page(template_path, output_path, data):
    with open(template_path) as _template:
        template = Template(_template.read())
        with open(output_path, 'w') as _output:
            _output.write(
                template.substitute(data)
            )

if __name__ == "__main__":
    make_page(
        'src/PAGE.html',
        '../index.html',
        data_builder()
    )

** TL;DR

Create a template file named `template.txt` like this:

#+BLOCKNAME: template.txt #+begin_src shell :tangle ~/Grimoire/_examples/template.txt

this is the name: $name and the color: $color

#+end_src

Then make this

#+BLOCKNAME: generator.py #+begin_src python :results output :dir ~/Grimoire/_examples :wrap example :post padder(data=*this*)

from string import Template

with open('template.txt') as _tmpl: template = Template(_tmpl.read()) output = template.substitute( name="Karl", color="Green" ) print(output)

#+end_src

Results

this is the name: Karl
  and the color: Green

** From A String

Code

from string import Template

skeleton = Template('Name: $name - Color: $color')

output = skeleton.substitute(
  name="Karl", 
  color="Green"
)

print(output)

Results

Name: Karl - Color: Green

#+REFERENCES:

docs: https://docs.python.org/3/library/string.html#template-strings