htmltools Library for HTML Generation

0.6.0 · active · verified Mon Apr 13

htmltools is a Python library providing tools for creating, manipulating, and writing HTML. It facilitates the programmatic generation of HTML structures, including tags, attributes, and dependencies. The library is currently at version 0.6.0 and is actively maintained by Posit, with a consistent release cadence to add features and address issues.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating a hierarchical HTML structure using `tags` functions, applying CSS styles with `css()`, defining an `HTMLDependency` for external assets, and rendering the combined output to a string using `TagList().get_html_string()`.

from htmltools import HTML, TagList, tags, HTMLDependency, css

# Create a simple HTML tag
my_div = tags.div(
    tags.h1('Hello, htmltools!'),
    tags.p('This is a paragraph generated programmatically.'),
    tags.a('Learn more', href='https://github.com/rstudio/py-htmltools'),
    _class='container',
    style=css(background_color='lightblue', padding='15px')
)

# Create an HTML dependency (e.g., for a CSS file)
my_dependency = HTMLDependency(
    name='my-custom-css',
    version='1.0.0',
    source={'package': 'my_app', 'subdir': 'assets'},
    stylesheet={'href': 'style.css'}
)

# Combine into a TagList and render
output_html = TagList(my_div, my_dependency).get_html_string()

print(output_html)

view raw JSON →