|
| 1 | +# Python HTML 5 Generator |
| 2 | + |
| 3 | +[](https://pypi.python.org/pypi/htmlgen/) |
| 4 | +[](https://github.com/srittau/python-htmlgen/releases/) |
| 5 | +[](https://pypi.python.org/pypi/htmlgen/) |
| 6 | +[](https://travis-ci.org/srittau/python-htmlgen) |
| 7 | + |
| 8 | +Library to generate HTML from classes. |
| 9 | + |
| 10 | +Basic usage: |
| 11 | + |
| 12 | + >>> from htmlgen import Division, Span |
| 13 | + >>> Division("This is ", Span("important!"), "!") |
| 14 | + |
| 15 | +A more verbose example: |
| 16 | + |
| 17 | + >>> span = Span("important") |
| 18 | + >>> span.add_css_classes("important") |
| 19 | + >>> div = Division() |
| 20 | + >>> div.id = "my-block" |
| 21 | + >>> div.append("This is ") |
| 22 | + >>> div.append(span) |
| 23 | + >>> div.append("!") |
| 24 | + |
| 25 | +A tree constructed like this can be converted to a string: |
| 26 | + |
| 27 | + >>> str(div) |
| 28 | + '<div id="my-block">This is <span class="important">important</span>!</div>' |
| 29 | + >>> "<p>This is {}!</p>".format(span) |
| 30 | + '<p>This is <span class="important">important</span>!</p>' |
| 31 | + |
| 32 | +Alternatively, all elements can be used as iterators, for example to return |
| 33 | +them from a WSGI callback: |
| 34 | + |
| 35 | + >>> def application(env, start_response): |
| 36 | + ... start_response("200 OK", [("Content-Type", "text/html")]) |
| 37 | + ... return div |
| 38 | + |
| 39 | +There are two different ways to render children of HTML elements. The tree |
| 40 | +construction approach shown above is mainly suitable for elements with few |
| 41 | +children. The disadvantage of this approach is that the whole tree must be |
| 42 | +constructed in memory. An alternative way, best suited for custom sub-classes |
| 43 | +of elements, is to override the generate_children method of the Element class: |
| 44 | + |
| 45 | + >>> class MyBlock(Division): |
| 46 | + ... def __init__(self): |
| 47 | + ... super(MyBlock, self).__init__() |
| 48 | + ... self.id = "my-block" |
| 49 | + ... def generate_children(self): |
| 50 | + ... yield "This is " |
| 51 | + ... span = Span("important") |
| 52 | + ... span.add_css_classes("important") |
| 53 | + ... yield span |
| 54 | + ... yield "!" |
| 55 | + >>> str(MyBlock()) |
| 56 | + '<div id="my-block">This is <span class="important">important</span>!</div>' |
0 commit comments