|
| 1 | + |
| 2 | + |
| 3 | +""" |
| 4 | +# tag::TAG_DEMO[] |
| 5 | +>>> tag('br') # <1> |
| 6 | +'<br />' |
| 7 | +>>> tag('p', 'hello') # <2> |
| 8 | +'<p>hello</p>' |
| 9 | +>>> print(tag('p', 'hello', 'world')) |
| 10 | +<p>hello</p> |
| 11 | +<p>world</p> |
| 12 | +>>> tag('p', 'hello', id=33) # <3> |
| 13 | +'<p id="33">hello</p>' |
| 14 | +>>> print(tag('p', 'hello', 'world', class_='sidebar')) # <4> |
| 15 | +<p class="sidebar">hello</p> |
| 16 | +<p class="sidebar">world</p> |
| 17 | +>>> tag(content='testing', name="img") # <5> |
| 18 | +'<img content="testing" />' |
| 19 | +>>> my_tag = {'name': 'img', 'title': 'Sunset Boulevard', |
| 20 | +... 'src': 'sunset.jpg', 'class': 'framed'} |
| 21 | +>>> tag(**my_tag) # <6> |
| 22 | +'<img class="framed" src="sunset.jpg" title="Sunset Boulevard" />' |
| 23 | +
|
| 24 | +# end::TAG_DEMO[] |
| 25 | +""" |
| 26 | + |
| 27 | + |
| 28 | +# tag::TAG_FUNC[] |
| 29 | +def tag(name, *content, class_=None, **attrs): |
| 30 | + """Generate one or more HTML tags""" |
| 31 | + if class_ is not None: |
| 32 | + attrs['class'] = class_ |
| 33 | + if attrs: |
| 34 | + attr_pairs = (f' {attr}="{value}"' for attr, value |
| 35 | + in sorted(attrs.items())) |
| 36 | + attr_str = ''.join(attr_pairs) |
| 37 | + else: |
| 38 | + attr_str = '' |
| 39 | + if content: |
| 40 | + elements = (f'<{name}{attr_str}>{c}</{name}>' |
| 41 | + for c in content) |
| 42 | + return '\n'.join(elements) |
| 43 | + else: |
| 44 | + return f'<{name}{attr_str} />' |
| 45 | +# end::TAG_FUNC[] |
0 commit comments