
166 views
Generate HTML using tinyhtml Module in Python
The tinyhtml
module in Python is a lightweight library for generating HTML documents. You can use it to create HTML content dynamically in your Python programs. To get started, you’ll need to install the tinyhtml
module:
Bash
pip install tinyhtml
Here’s an example of how to generate HTML using the tinyhtml
module:
Python
from tinyhtml import HTML, Text, render
# Create an HTML document
doc = HTML(
head=HTML(
title=Text("My HTML Document")
),
body=HTML(
h1=Text("Welcome to my website"),
p=Text("This is a simple example of generating HTML using tinyhtml."),
a={"href": "https://www.example.com", "target": "_blank"}(
Text("Visit Example.com")
),
ul=HTML(
li=Text("Item 1"),
li=Text("Item 2"),
li=Text("Item 3"),
),
)
)
# Render the HTML document to a string
html_str = render(doc)
# Print the generated HTML
print(html_str)
In this example:
- We import the necessary classes and functions from the
tinyhtml
module. - We create an HTML document using the
HTML
class. The document structure is defined with nested calls toHTML
. Text content is provided using theText
class. - We specify HTML elements, their attributes, and their content within the
HTML
structure. For example, we create anh1
element with the title “Welcome to my website.” - We can also use attributes within an element, as shown in the
a
element, which includes anhref
attribute. - Finally, we render the HTML document to a string using the
render
function.
When you run this code, it will generate and print an HTML document as a string. You can use this generated HTML in various ways, such as serving it as a webpage using a web framework or writing it to an HTML file.