Skip to main content

Simple HTML generation

Project description

Simple HTML generation

PyPI

Installation

Install the minihtml package from PyPI:

$ pip install minihtml

Examples

Create a minihtml.Html instance to produce tags. Tags stringify to HTML:

>>> from minihtml import Html
>>> h = Html()
>>> html = h.html(h.head(h.title("Hello, World!")))
>>> print(html)
<html><head><title>Hello, World!</title></head></html>

Tags are callables that accept positional arguments (children) and keyword arguments (attributes). Calls can be chained to produce code that is structured more like HTML (attributes before content):

>>> print(h.a("link title", href="/url"))
<a href="/url">link title</a>
>>> print(h.a(href="/url")("link title"))
<a href="/url">link title</a>

There are shortcuts for setting the class and id attributes using [] accessors:

>>> print(h.div["#header bg-white"](h.span["text-xl font-medium"]("hello")))
<div id="header" class="bg-white"><span class="text-xl font-medium">hello</span></div>

Text content, attribute names and attribute values are escaped automatically. To include unescaped content, use the raw element. Only use this with trusted input:

>>> print(h.div(foo='"bar"')("2 > 1"))
<div foo="&quot;bar&quot;">2 &gt; 1</div>
>>> print(h.script(h.raw('if (2 > 1) console.log("math still works");')))
<script>if (2 > 1) console.log("math still works");</script>

To use tag or attribute names that conflict with python keywords, append an underscore. Underscores within attribute names are converted to hyphens ("-"):

>>> print(h.del_("deleted text"))
<del>deleted text</del>
>>> print(h.label(for_="fieldname")("text"))
<label for="fieldname">text</label>
>>> print(h.span(data_foo="bar"))
<span data-foo="bar"></span>

Attributes that have no value can be set by passing the value True:

>>> print(h.input(type="text", disabled=True))
<input type="text" disabled />

Use minihtml.tostring to convert a tag to a string and add a doctype:

>>> from minihtml import tostring
>>> html = h.html(h.body("my website"))
>>> tostring(html)
'<!doctype html>\n<html><body>my website</body></html>\n'

License

minihtml is licensed under the MIT license. See the included file LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

minihtml-0.1.2.tar.gz (7.6 kB view hashes)

Uploaded Source

Built Distribution

minihtml-0.1.2-py3-none-any.whl (5.5 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page