Simple HTML template in Python

Well django has very nice powerful templating engine, that's purpose is separating HTML from python logic (but that would require you to use django altogether, so it might be an overkill if you just want templating).

If your templates are really easy (no loops) you might use native python string.format function (I used it in a side project that generated config files to some Fortran code, and it wasn't so bad).

Other choice might be jinja2 that is really close to django templates, but standalone and more powerful.


Might I suggest looking at web2py as well? At the most basic level you could simple have your colleague create the html file then where ever you need data replace it with {{=var}} the var can be retrieved by the web2py controller which is written in a python function. From the function you could put together your data and return it the html view with "return dict(var=var)".

If your view looked like this:

<html>
    <head>
        <title>some title</title>
    </head>
    <body>
        <h1>{{=message}}</h1>
    </body>
</html>

The controller could look like this:

def index():
    message = "Hello World"
    return dict(message=message)

You could also use django, as other have mentioned but check the link for some web2py documentation


The simple template in python is: https://docs.python.org/3.6/library/string.html#template-strings

It comes with the language, no need for external libraries.

Here is an example of how to use a Template:

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
...
ValueError: Invalid placeholder in string: line 1, col 11
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'