Package: dominate
DominateDominateis 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:importdominatefromdominate.tagsimport*doc=dominate.document(title='Dominate your HTML')withdoc.head:link(rel='stylesheet',href='style.css')script(type='text/javascript',src='script.js')withdoc:withdiv(id='header').add(ol()):foriin['home','about','contact']:li(a(i.title(),href='/%s.html'%i))withdiv():attr(cls='body')p('Lorem ipsum..')print(doc)Output:<!DOCTYPE html><html><head><title>Dominate your HTML</title><linkhref="style.css"rel="stylesheet"><scriptsrc="script.js"type="text/javascript"></script></head><body><divid="header"><ol><li><ahref="/home.html">Home</a></li><li><ahref="/about.html">About</a></li><li><ahref="/contact.html">Contact</a></li></ol></div><divclass="body"><p>Lorem ipsum..</p></div></body></html>InstallationThe recommended way to installdominateis withpip:pip install dominateDeveloped ByTom Flanagan -tom@zkpq.caJake Wharton -jakewharton@gmail.comBrad JankeGit repository located atgithub.com/Knio/dominateExamplesAll examples assume you have imported the appropriate tags or entire tag set:fromdominate.tagsimport*Hello, World!The most basic feature ofdominateexposes 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.print(html(body(h1('Hello, World!'))))<html><body><h1>Hello, World!</h1></body></html>AttributesDominatecan 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 attributesclassandforwhich conflict with Python'sreserved keywords, you can use the following aliases:classfor_class_forclsfrclassNamehtmlForclass_namehtml_fortest=label(cls='classname anothername',fr='someinput')print(test)<labelclass="classname anothername"for="someinput"></label>Usedata_*forcustom HTML5 data attributes.test=div(data_employee='101011')print(test)<divdata-employee="101011"></div>You can also modify the attributes of tags through a dictionary-like interface:header=div()header['id']='header'print(header)<divid="header"></div>Complex StructuresThrough the use of the+=operator and the.add()method you can easily create more advanced structures.Create a simple list:list=ul()foriteminrange(4):list+=li('Item #',item)print(list)<ul><li>Item #0</li><li>Item #1</li><li>Item #2</li><li>Item #3</li></ul>dominatesupports iterables to help streamline your code:print(ul(li(a(name,href=link),__pretty=False)forname,linkinmenu_items))<ul><li><ahref="/home/">Home</a></li><li><ahref="/about/">About</a></li><li><ahref="/downloads/">Downloads</a></li><li><ahref="/links/">Links</a></li></ul>A simple document tree:_html=html()_body=_html.add(body())header=_body.add(div(id='header'))content=_body.add(div(id='content'))footer=_body.add(div(id='footer'))print(_html)<html><body><divid="header"></div><divid="content"></div><divid="footer"></div></body></html>For clean code, the.add()method returns children in tuples. The above example can be cleaned up and expanded like this:_html=html()_head,_body=_html.add(head(title('Simple Document Tree')),body())names=['header','content','footer']header,content,footer=_body.add([div(id=name)fornameinnames])print(_html)<html><head><title>Simple Document Tree</title></head><body><divid="header"></div><divid="content"></div><divid="footer"></div></body></html>You can modify the attributes of tags through a dictionary-like interface:header=div()header['id']='header'print(header)<divid="header"></div>Or the children of a tag though an array-line interface:header=div('Test')header[0]='Hello World'print(header)<div>Hello World</div>Comments can be created using objects too!print(comment('BEGIN HEADER'))<!--BEGIN HEADER-->print(comment(p('Upgrade to newer IE!'),condition='lt IE9'))<!--[if lt IE9]><p>Upgrade to newer IE!</p><![endif]-->RenderingBy 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.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()withd:hr()p("Test")br()print(d.render())print(d.render(xhtml=True))<div><hr><p>Test</p><br></div><div><hr/><p>Test</p><br/></div>Context ManagersYou can also add child elements using Python'swithstatement:h=ul()withh:li('One')li('Two')li('Three')print(h)<ul><li>One</li><li>Two</li><li>Three</li></ul>You can use this along with the other mechanisms of adding children elements, including nestingwithstatements, and it works as expected:h=html()withh.add(body()).add(div(id='content')):h1('Hello World!')p('Lorem ipsum ...')withtable().add(tbody()):l=tr()l+=td('One')l.add(td('Two'))withl:td('Three')print(h)<html><body><divid="content"><h1>Hello World!</h1><p>Lorem ipsum ...</p><table><tbody><tr><td>One</td><td>Two</td><td>Three</td></tr></tbody></table></div></body></html>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 theattrfunction:d=div()withd:attr(id='header')print(d)<divid="header"></div>And text nodes can be added with thedominate.util.textfunction:fromdominate.utilimporttextpara=p(__pretty=False)withpara:text('Have a look at our ')a('other products',href='/products')print(para)<p>Have a look at our<ahref="/products">other products</a></p>DecoratorsDominateis great for creating reusable widgets for parts of your page. Consider this example:defgreeting(name):withdiv()asd:p('Hello,%s'%name)returndprint(greeting('Bob'))<div><p>Hello, Bob</p></div>You can see the following pattern being repeated here:defwidget(parameters):withtag()ast:...returntThis boilerplate can be avoided by using tags (objects and instances) as decorators@divdefgreeting(name):p('Hello%s'%name)print(greeting('Bob'))<div><p>Hello Bob</p></div>The decorated function will return a new instance of the tag used to decorate it, and execute in awithcontext 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.@div(h2('Welcome'),cls='greeting')defgreeting(name):p('Hello%s'%name)print(greeting('Bob'))<divclass="greeting"><h2>Welcome</h2><p>Hello Bob</p></div>Creating DocumentsSince 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.d=document()print(d)<!DOCTYPE html><html><head><title>Dominate</title></head><body></body></html>Thedocumentclass acceptstitle,doctype, andrequestkeyword arguments.
The default values for these arguments areDominate,<!DOCTYPE html>, andNonerespectively.Thedocumentclass also provides helpers to allow you to access thetitle,head, andbodynodes directly.d=document()>>>d.head<dominate.tags.head:0attributes,1children>>>>d.body<dominate.tags.body:0attributes,0children>>>>d.titleu'Dominate'Thedocumentclass also provides helpers to allow you to directly add nodes to thebodytag.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 HTMLIf 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.SVGThedominate.svgmodule contains SVG tags similar to howdominate.tagscontains HTML tags. SVG elements will automatically convert_to-for dashed elements. For example:fromdominate.svgimport*print(circle(stroke_width=5))<circlestroke-width="5"></circle>