File: README.md

package info (click to toggle)
dominate 2.3.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 172 kB
  • sloc: python: 1,743; makefile: 6
file content (546 lines) | stat: -rw-r--r-- 11,419 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
Dominate
========

`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:

```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)
```

Output:

```html
<!DOCTYPE html>
<html>
  <head>
    <title>Dominate your HTML</title>
    <link href="style.css" rel="stylesheet">
    <script src="script.js" type="text/javascript"></script>
  </head>
  <body>
    <div id="header">
      <ol>
        <li>
          <a href="/home.html">Home</a>
        </li>
        <li>
          <a href="/about.html">About</a>
        </li>
        <li>
          <a href="/contact.html">Contact</a>
        </li>
      </ol>
    </div>
    <div class="body">
      <p>Lorem ipsum..</p>
    </div>
  </body>
</html>
```


Compatibility
-------------

`Dominate` is compatible with both Python 2.7 and Python 3.3. There are known issues with Python 3.2 and below.

[![Build Status](https://travis-ci.org/Knio/dominate.png?branch=master)](https://travis-ci.org/Knio/dominate)
[![Coverage Status](https://coveralls.io/repos/Knio/dominate/badge.png?branch=master)](https://coveralls.io/r/Knio/dominate?branch=master)



Installation
------------

The recommended way to install `dominate` is with
[`pip`](http://pypi.python.org/pypi/pip/):

    sudo pip install dominate

[![PyPI version](https://badge.fury.io/py/dominate.png)](http://badge.fury.io/py/dominate)


Developed By
------------

* Tom Flanagan - <tom@zkpq.ca>
* Jake Wharton - <jakewharton@gmail.com>
* [Brad Janke](//github.com/bradj)

Git repository located at
[github.com/Knio/dominate](//github.com/Knio/dominate)


Examples
========

All examples assume you have imported the appropriate tags or entire tag set:

```python
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.

```python
print(html(body(h1('Hello, World!'))))
```
```html
<html>
    <body>
        <h1>Hello, World!</h1>
    </body>
</html>
```

Attributes
----------

`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](http://docs.python.org/2/reference/lexical_analysis.html#keywords "Reserved Keywords"), you can use the following aliases:

| class | for |
|-------|-----|
|_class | _for |
|cls | fr |
|className|htmlFor|
|class_name|html_for|


```python
test = label(cls='classname anothername', fr='someinput')
print(test)
```
```html
<label class="classname anothername" for="someinput"></label>
```

Use `data_*` for [custom HTML5 data attributes](http://www.w3.org/html/wg/drafts/html/master/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes "HTML5 Data Attributes").

```python
test = div(data_employee='101011')
print(test)
```
```html
<div data-employee="101011"></div>
```

You can also modify the attributes of tags through a dictionary-like interface:

```python
header = div()
header['id'] = 'header'
print(header)
```
```html
<div id="header"></div>
```

Complex Structures
------------------

Through the use of the `+=` operator and the `.add()` method you can easily create more advanced structures.

Create a simple list:

```python
list = ul()
for item in range(4):
    list += li('Item #', item)
print(list)
```
```html
<ul>
    <li>Item #0</li>
    <li>Item #1</li>
    <li>Item #2</li>
    <li>Item #3</li>
</ul>
```

`dominate` supports iterables to help streamline your code:

```python
print(ul(li(a(name, href=link), __pretty=False) for name, link in menu_items))
```
```html
<ul>
    <li><a href="/home/">Home</a></li>
    <li><a href="/about/">About</a></li>
    <li><a href="/downloads/">Downloads</a></li>
    <li><a href="/links/">Links</a></li>
</ul>
```

A simple document tree:

```python
_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
<html>
    <body>
        <div id="header"></div>
        <div id="content"></div>
        <div id="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:

```python
_html = html()
_head, _body = _html.add(head(title('Simple Document Tree')), body())
names = ['header', 'content', 'footer']
header, content, footer = _body.add(div(id=name) for name in names)
print(_html)
```
```html
<html>
    <head>
       <title>Simple Document Tree</title>
    </head>
    <body>
        <div id="header"></div>
        <div id="content"></div>
        <div id="footer"></div>
    </body>
</html>
```

You can modify the attributes of tags through a dictionary-like interface:

```python
header = div()
header['id'] = 'header'
print(header)
```
```html
<div id="header"></div>
```

Or the children of a tag though an array-line interface:

```python
header = div('Test')
header[0] = 'Hello World'
print(header)
```
```html
<div>Hello World</div>
```

Comments can be created using objects too!

```python
print(comment('BEGIN HEADER'))
```
```html
<!--BEGIN HEADER-->
```

```python
print(comment(p('Upgrade to newer IE!'), condition='lt IE9'))
```
```html
<!--[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.

```python
a = div(span('Hello World'))
print(a.render())
```
```html
<div>
  <span>Hello World</span>
</div>
```
```python
print(a.render(pretty=False))
```
```html
<div><span>Hello World</span></div>
```
```python
print(a.render(indent='\t'))
```
```html
<div>
	<span>Hello World</span>
</div>
```
```python
a = div(span('Hello World'), __pretty=False)
print(a.render())
```
```html
<div><span>Hello World</span></div>
```
```python
d = div()
with d:
    hr()
    p("Test")
    br()
print(d.render())
print(d.render(xhtml=True))
```
```html
<div>
  <hr>
  <p>Test</p><br>
</div>
<div>
  <hr />
  <p>Test</p><br />
</div>
```


Context Managers
----------------

You can also add child elements using Python's `with` statement:

```python
h = ul()
with h:
    li('One')
    li('Two')
    li('Three')

print(h)
```
```html
<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 nesting `with` statements, and it works as expected:

```python
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)
```
```html
<html>
    <body>
        <div id="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 the `attr` function:

```python
d = div()
with d:
    attr(id='header')

 print(d)
 ```
 ```html
<div id="header"></div>
```


Decorators
----------

`Dominate` is great for creating reusable widgets for parts of your page. Consider this example:

```python
def greeting(name):
    with div() as d:
        p('Hello, %s' % name)
    return d

print(greeting('Bob'))
```
```html
<div>
    <p>Hello, Bob</p>
</div>
```

You can see the following pattern being repeated here:

```python
def widget(parameters):
    with tag() as t:
        ...
    return t
```

This boilerplate can be avoided by using tags (objects and instances) as decorators

```python
@div
def greeting(name):
    p('Hello %s' % name)
print(greeting('Bob'))
```
```html
<div>
    <p>Hello Bob</p>
</div>
```

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.

```python
@div(h2('Welcome'), cls='greeting')
def greeting(name):
    p('Hello %s' % name)

print(greeting('Bob'))
```
```html

<div class="greeting">
    <h2>Welcome</h2>
    <p>Hello Bob</p>
</div>
```

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.

```python
d = document()
print(d)
```
```html
<!DOCTYPE html>
<html>
    <head>
       <title>Dominate</title>
    </head>
    <body></body>
</html>
```

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 `html`, `head`, and `body` nodes directly.

```python
d = document()
```

```python
>>> d.html
<dominate.tags.html: 0 attributes, 2 children>
>>> d.head
<dominate.tags.head: 0 attributes, 0 children>
>>> d.body
<dominate.tags.body: 0 attributes, 0 children>
```


You should notice that here the `head` tag contains zero children.
This is because the default `title` tag is only added when the document is rendered and the `head` element does not explicitly contain one.

The `document` class also provides helpers to allow you to directly add nodes to the `body` tag.

```python
d = document()
d += h1('Hello, World!')
d += p('This is a paragraph.')
print(d)
```
```html
<!DOCTYPE html>
<html>
    <head>
       <title>Dominate</title>
    </head>
    <body>
        <h1>Hello, World!</h1>
        <p>This is a paragraph.</p>
    </body>
</html>
```