Dominate is a Python library for creating and manipulating HTML documents using an elegant DOM API.
It allows you to write HTML pages in pure Python very concisely, which eliminates the need to learn another template language, and lets you take advantage of the more powerful features of Python.
Python:
import dominate
from dominate.tags import *
doc = dominate.document(title='Dominate your HTML')
with doc.head:
link(rel='stylesheet', href='style.css')
script(type='text/javascript', src='script.js')
with doc:
with div(id='header').add(ol()):
for i in ['home', 'about', 'contact']:
li(a(i.title(), href='/%s.html' % i))
with div():
attr(cls='body')
p('Lorem ipsum..')
print(doc)
All examples assume you have imported the appropriate tags or entire tag set:
from dominate.tags import *
Hello, World!
The most basic feature of dominate exposes a class for each HTML element, where the constructor
accepts child elements, text, or keyword attributes. dominate nodes return their HTML representation
from the __str__, __unicode__, and render() methods.
Dominate can also use keyword arguments to append attributes onto your tags. Most of the attributes are a direct copy from the HTML spec with a few variations.
For attributes class and for which conflict with Python’s reserved keywords, you can use the following aliases:
class
for
_class
_for
cls
fr
className
htmlFor
class_name
html_for
test = label(cls='classname anothername', fr='someinput')
print(test)
print(comment(p('Upgrade to newer IE!'), condition='lt IE9'))
<!--[if lt IE9]>
<p>Upgrade to newer IE!</p>
<![endif]-->
Rendering
By default, render() tries to make all output human readable, with one HTML
element per line and two spaces of indentation.
This behavior can be controlled by the __pretty (default: True except for
certain element types like pre) attribute when creating an element, and by
the pretty (default: True), indent (default: ) and xhtml (default: False)
arguments to render(). Rendering options propagate to all descendant nodes.
a = div(span('Hello World'))
print(a.render())
<div>
<span>Hello World</span>
</div>
print(a.render(pretty=False))
<div><span>Hello World</span></div>
print(a.render(indent='\t'))
<div>
<span>Hello World</span>
</div>
a = div(span('Hello World'), __pretty=False)
print(a.render())
<div><span>Hello World</span></div>
d = div()
with d:
hr()
p("Test")
br()
print(d.render())
print(d.render(xhtml=True))
You can use this along with the other mechanisms of adding children elements, including nesting with statements, and it works as expected:
h = html()
with h.add(body()).add(div(id='content')):
h1('Hello World!')
p('Lorem ipsum ...')
with table().add(tbody()):
l = tr()
l += td('One')
l.add(td('Two'))
with l:
td('Three')
print(h)
The decorated function will return a new instance of the tag used to decorate it, and execute in a with context which will collect all the nodes created inside it.
You can also use instances of tags as decorators, if you need to add attributes or other data to the root node of the widget.
Each call to the decorated function will return a copy of the node used to decorate it.
Since creating the common structure of an HTML document everytime would be excessively tedious dominate provides a class to create and manage them for you: document.
When you create a new document, the basic HTML tag structure is created for you.
The document class accepts title, doctype, and request keyword arguments.
The default values for these arguments are Dominate, <!DOCTYPE html>, and None respectively.
The document class also provides helpers to allow you to access the title, head, and body nodes directly.
The document class also provides helpers to allow you to directly add nodes to the body tag.
d = document()
d += h1('Hello, World!')
d += p('This is a paragraph.')
print(d)
<!DOCTYPE html>
<html>
<head>
<title>Dominate</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</body>
</html>
Embedding HTML
If you need to embed a node of pre-formed HTML coming from a library such as markdown or the like you can avoid escaped HTML by using the raw method from the dominate.util package:
from dominate.util import raw
...
td(raw('<a href="example.html">Example</a>'))
Without the raw call, this code would render escaped HTML with lt, etc. The behavior of the previous block of code is the same as td_element.innerHTML="<a href="example.html">Example</a>" in JavaScript.
SVG
The dominate.svg module contains SVG tags similar to how dominate.tags contains HTML tags. SVG elements will automatically convert _ to - for dashed elements. For example:
from dominate.svg import *
print(circle(stroke_width=5))
Dominate
Dominateis a Python library for creating and manipulating HTML documents using an elegant DOM API. It allows you to write HTML pages in pure Python very concisely, which eliminates the need to learn another template language, and lets you take advantage of the more powerful features of Python.Python:
Output:
Installation
The recommended way to install
dominateis withpip:Developed By
Git repository located at github.com/Knio/dominate
Examples
All examples assume you have imported the appropriate tags or entire tag set:
Hello, World!
The most basic feature of
dominateexposes a class for each HTML element, where the constructor accepts child elements, text, or keyword attributes.dominatenodes return their HTML representation from the__str__,__unicode__, andrender()methods.Attributes
Dominatecan also use keyword arguments to append attributes onto your tags. Most of the attributes are a direct copy from the HTML spec with a few variations.For attributes
classandforwhich conflict with Python’s reserved keywords, you can use the following aliases:Use
data_*for custom HTML5 data attributes.You can also modify the attributes of tags through a dictionary-like interface:
Complex Structures
Through the use of the
+=operator and the.add()method you can easily create more advanced structures.Create a simple list:
dominatesupports iterables to help streamline your code:A simple document tree:
For clean code, the
.add()method returns children in tuples. The above example can be cleaned up and expanded like this:You can modify the attributes of tags through a dictionary-like interface:
Or the children of a tag though an array-line interface:
Comments can be created using objects too!
Rendering
By default,
render()tries to make all output human readable, with one HTML element per line and two spaces of indentation.This behavior can be controlled by the
__pretty(default:Trueexcept for certain element types likepre) attribute when creating an element, and by thepretty(default:True),indent(default:) andxhtml(default:False) arguments torender(). Rendering options propagate to all descendant nodes.Context Managers
You can also add child elements using Python’s
withstatement:You can use this along with the other mechanisms of adding children elements, including nesting
withstatements, and it works as expected:When the context is closed, any nodes that were not already added to something get added to the current context.
Attributes can be added to the current context with the
attrfunction:And text nodes can be added with the
dominate.util.textfunction:Decorators
Dominateis great for creating reusable widgets for parts of your page. Consider this example:You can see the following pattern being repeated here:
This boilerplate can be avoided by using tags (objects and instances) as decorators
The decorated function will return a new instance of the tag used to decorate it, and execute in a
withcontext which will collect all the nodes created inside it.You can also use instances of tags as decorators, if you need to add attributes or other data to the root node of the widget. Each call to the decorated function will return a copy of the node used to decorate it.
Creating Documents
Since creating the common structure of an HTML document everytime would be excessively tedious dominate provides a class to create and manage them for you:
document.When you create a new document, the basic HTML tag structure is created for you.
The
documentclass acceptstitle,doctype, andrequestkeyword arguments. The default values for these arguments areDominate,<!DOCTYPE html>, andNonerespectively.The
documentclass also provides helpers to allow you to access thetitle,head, andbodynodes directly.The
documentclass also provides helpers to allow you to directly add nodes to thebodytag.Embedding HTML
If you need to embed a node of pre-formed HTML coming from a library such as markdown or the like you can avoid escaped HTML by using the raw method from the dominate.util package:
Without the raw call, this code would render escaped HTML with lt, etc. The behavior of the previous block of code is the same as
td_element.innerHTML="<a href="example.html">Example</a>"in JavaScript.SVG
The
dominate.svgmodule contains SVG tags similar to howdominate.tagscontains HTML tags. SVG elements will automatically convert_to-for dashed elements. For example: