Python Tinyhtml – Create HTML Documents With Python

I keep coming back to tinyhtml whenever I need to generate HTML from Python without the overhead of a full template engine. The library is small, fast, and does exactly one thing well.

In this article, I walk through generating HTML documents with the tinyhtml module, from raw string concatenation to the programmatic HTML building approach that tinyhtml enables.

TLDR

  • tinyhtml is a lightweight Python library for building HTML programmatically
  • Use html() and render() to create and output HTML documents
  • Use h() to build HTML elements with attributes and content
  • Use frag() to generate HTML fragments without a full document wrapper
  • Conditional logic and CSS classes work through Python expressions, not HTML-specific syntax

How to Write Raw HTML to a File Using Python

The simplest approach to generating HTML in Python is building the string manually and writing it to a file. Here is a basic example that creates an HTML document with a title, header, and body:


html = """<html>
  <head>
    <title>AskPython</title>
  </head>
  <body>
    <h1>Welcome to AskPython</h1>
    <p>This is an article about generating HTML docs using python</p>
  </body>
</html>
"""
with open("askpython.html", "w") as f:
    f.write(html)

The open() function with “w” mode writes HTML to the file “askpython.html”. Running this creates a file in the same directory containing:


<html>
  <head>
    <title>AskPython</title>
  </head>
  <body>
    <h1>Welcome to AskPython</h1>
    <p>This is an article about generating HTML docs using python</p>
  </body>
</html>

For more on file handling in Python, see Python File Handling.

The tinyhtml Module for HTML Documents

tinyhtml is a Python library that safely renders compact HTML5 from Python expressions. Rather than stitching together HTML strings, you build a document tree using Python function calls. The library handles proper escaping and produces valid HTML output. Key functions are html(), render(), h(), and frag().

Installing tinyhtml

Install tinyhtml with pip:


pip install tinyhtml

1. Using html() and render() to Declare and Render Basic HTML

The html() function declares an HTML document. Call it with attributes and use render() to output the final HTML string:


from tinyhtml import html

html_content = html(lang="en")()
print(html_content.render())

Here is what is happening in this code:

  • html(lang=”en”)() creates an HTML element with the lang attribute set to “en”
  • The inner () after html() means no child elements are added to the html element
  • render() converts the HTML element to a string
  • print() outputs the resulting HTML string

Output:


<!DOCTYPE html><html lang="en"></html>

2. Using the h() Function to Generate HTML Elements

The h() function is the main tool for building HTML elements. It handles attributes, regular elements, and self-closing elements:


from tinyhtml import html, h

html_content = html(lang="en")(
    h("h1")("Lorem ipsum"),
    h("p")("dolor sit amet."),
    h("br")
)
print(html_content.render())

Here is what this does:

  • The outer html(lang=”en”)() creates the document wrapper with a lang attribute
  • h(“h1”)(“Lorem ipsum”) creates an h1 element with text content
  • h(“p”)(“dolor sit amet.”) creates a p element with text content
  • h(“br”) creates a self-closing br (line break) element with no content
  • render() converts the entire element tree to an HTML string

Output:


<!DOCTYPE html><html lang="en"><h1>Lorem ipsum</h1><p>dolor sit amet.</p><br></html>

3. Using frag() to Generate HTML Fragments

Sometimes you do not need a full HTML document, just a fragment of HTML to embed elsewhere. The frag() function creates a fragment from multiple elements without wrapping them in html or DOCTYPE tags:


from tinyhtml import h, frag

content = frag(
    h("h1")("Lorem ipsum"),
    h("p")("dolor sit amet."),
)
print(content.render())

Here is how this works:

  • frag() creates a fragment from multiple elements without html or DOCTYPE wrapper
  • h(“h1”) and h(“p”) build individual elements within the fragment
  • render() converts the fragment to an HTML string

Output:


<h1>Lorem ipsum</h1><p>dolor sit amet.</p>

4. Adding Conditional Statements

Since HTML building in tinyhtml uses Python expressions, conditional logic works naturally with standard Python if-else statements:


from tinyhtml import h

score = input("Input your score(out of 100): ")
passing_marks = 33

conditional_html = h("h1")(
    h("p")("Passed")
    if int(score) > passing_marks
    else "Failed",
    h("p")("Thank you!")
)
print(conditional_html.render())

Here is how this works:

  • input() prompts the user for a score out of 100
  • The passing threshold is set to 33
  • A Python conditional expression (if-else) determines whether the p element shows “Passed” or “Failed”
  • render() outputs the final HTML string with the conditional content resolved

Output (when input is 45):


Input your score(out of 100): 45
<h1><p>Passed</p><p>Thank you!</p></h1>

5. Adding CSS Classes to Elements

CSS classes in tinyhtml use the klass operator instead of class, since class is a reserved keyword in Python. For attributes that map to Python reserved words, a trailing underscore suffix is used:


from tinyhtml import h

html_doc = h("h1")(
    h("p", klass="p1")("Sample text"),
    h("input", for_="firstName")()
)
print(html_doc.render())

The output shows the correct HTML with class=”p1″ on the paragraph and for=”firstName” on the input element:

Output:


<h1><p class="p1">Sample text</p><input for="firstName"></input></h1>

FAQ

Q: What is tinyhtml used for?

tinyhtml is used for programmatically generating HTML documents in Python. It provides a safe alternative to string concatenation by handling escaping automatically and producing valid HTML5 output.

Q: How does tinyhtml differ from template engines like Jinja2?

tinyhtml builds HTML through Python function calls rather than template syntax. There is no template markup to learn. For simple HTML generation tasks where a full template engine is overkill, tinyhtml is a lighter option.

Q: Can tinyhtml handle HTML escaping?

Yes. tinyhtml automatically escapes content passed to element constructors, preventing XSS issues when inserting user data into HTML.

Q: What Python version does tinyhtml support?

tinyhtml supports Python 3.6 and later. It has no external dependencies and installs cleanly via pip.

Conclusion

In this article, I generated HTML documents using tinyhtml, starting from raw string writing to programmatic HTML building with h(), html(), render(), and frag(). The library handles escaping automatically, making it safer than string concatenation for user-generated content. For related reading, see Pandas to HTML.

References:

https://pypi.org/project/tinyhtml/

Ashutosh Yadav
Ashutosh Yadav
Articles: 30