Which way to output string from template engine

What is the best (most Pythonic) way to output a string of HTML from a template engine?

By just writing to an output variable string:

outHTML = ""

outHTML += "<HTML line 1>\n"
outHTML += "<HTML line 2>\n"
outHTML += "<HTML line 3>\n"

print("outHTML2:", outHTML)

or by redirecting stdout and using either ‘print()’ or ‘.write()’:

from io import StringIO
import sys

old_stdout = sys.stdout
sys.stdout = oHTML= StringIO()

print("<HTML line 1>")
oHTML.write("<HTML line 2>")
print("<HTML line 3>")

sys.stdout = old_stdout
outHTML = oHTML.getvalue()
print("outHTML1:", outHTML)

Code which replaces sys.stdout is disruptive and StringIO is typically too verbose for concatenation unless it’s being passed to or from code which already operates on files.

Using += should be fine for small run-once scripts and smaller strings. For larger templates one should append the strings to a list and then join them at the end:

outHTML: list[str] = []

outHTML.append("<HTML line 1>\n")
outHTML.append("<HTML line 2>\n")
outHTML.append("<HTML line 3>\n")

print("outHTML:", "".join(outHTML))

This is the second post that you are posting on how to generate HTML page using Python.
If we know exactly what you want, we might be better able to help you.
For example, do you need an HTML page with - JavaScript in it?

  • What do you need Python for?

Creating a simplistic WSGI webserver and template engine.

I can only suggest you to use a framework.