Use Python's Built-In Template Strings To Generate Output
Basic example without a function
from string import Template
data = { "VALUE": "quick fox" }
skeleton = """The value is: $VALUE"""
template = Template(skeleton)
output = template.substitute(data)
print(output)
The value is: quick fox
** TODO: make example with this
This is a basic one where you pass it two paths and a data dictionary and it makes the output.
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:
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
this is the name: Karl and the color: Green
** From A String
from string import Template
skeleton = Template('Name: $name - Color: $color')
output = skeleton.substitute(
name="Karl",
color="Green"
)
print(output)
Name: Karl - Color: Green
#+REFERENCES:
docs: https://docs.python.org/3/library/string.html#template-strings