Mako for Python Templating Not a python but a snake anyway

Mako does templating for Python, for when you need to build a web page, and want to customize it with user data.

You add a header in your Python program to call the Mako library:

from mako.template import Template

Template can be used to create a Python data structure of your text:

TheText = Template("hello world!")
This data structure recognizes placeholders for variables you fill in. This is the format...
That can be embedded in the template:
from mako.template import Template

## Create a Variable
SubjectName = "Walter"

## Set the Mako variable "ThisGuysName" within the text body...
mytemplate = Template("Your name is ${ThisGuysName}!")

#Assign the Mako variable to the Python variable in this format, MakoVariable=PythonVariable

Template's "render" function creates the Python object, with the variables names, as well as a buffer to capture output.

Note: The Python variable name can be the same as the Mako variable name (I made the names separate for clarity). You still have to assign the Python variable to the Mako one i.e. "mytemplate.render(SubjectName=SubjectName)."

Loading Templates from Files: A template, with embedded variables, can be loaded from a file, using Template's 'filename' argument:

from mako.template import Template

SubjectName = "Walter"

mytemplate = Template(filename='MyTemplate.txt')
#MyTemplate.txt contains the line "Your name is ${ThisGuysName}!"


A template, with the variables filled in, can then be written to a file:

from mako.template import Template

#Set the template file to a variable
mytemplate = Template(filename='MyTemplate.txt')
#Fill in the variables
FilledTemplate = mytemplate.render(SubjectName=ThisGuysName)

#Create a file:
FileName = "NamingNames.txt"
f= open(FileName,"w+")

#Write template data to the file created

#Close file

For working code, check my GitHub page; For more details, see the docs.

Programming and System Administration Home