Skip to main content

pythonic way to create HTML/XML/SVG

Project description

pTag

ci-badge pypi-badge MIT-badge black-badge

pythonic way to create HTML/XML/SVG tag

  • create tags in pure python
  • use context manager for tag hierarchy
  • no external dependencies
  • read the docs

Quick Start

Installation: pip install ptag

from ptag import div, img, form, label, input_, del_
from ptag import Tag  # for creating custom element

# === html element ===
tag = div(img(src="url"), id="bar")
print(tag)  # <div id="bar"><img src="url"/></div>

# === custom element ===
my_tag = Tag("MyTag", child="foo", attr="bar")
print(my_tag)  # <MyTag attr="bar">foo</MyTag>

# == ⭐️ context manager ⭐️ ==
with form() as f:
    label("foo", for_="bar")  # python keyword 'for' -> 'for_'
    input_(None, name="bar", type="checkbox", value="baz")

print(f.pretty())
# <form>
#     <label for="bar">foo</label>
#     <input name="bar" type="checkbox" value="baz"/>
# </form>

# === add content and attributes to existing tag ===
# position args -> attribute w/o value
# python keyword 'class' -> 'class_'
tag = div(class_="foo") 
# python keyword 'del' -> 'del_'
tag.add(del_("bar"), "m-2", "rounded", id="baz") 
print(tag)  
# <div m-2 rounded class="foo" id="baz"><del>bar</del></div>

more examples could be found on references and tests

Limitations

  • add trailing underscore to work around python keywords and built-in object
    • tag attributes: class_, for_
    • tag object: del_, input_, map_, object_
  • prettify() method doesn't support attribute w/o value
    • eg. use kwargs selected="" instead of positional args selected

Motivation

When working with HTML, instead of separating python and template files like this:

<ul id="navigation">
    {% for item in navigation %}
    <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
    {% endfor %}
</ul>

I prefer a pythonic approach like this:

with ul(id="navigation") as nav:
    for item in navigation:
        li(a(item.caption, href=item.href))

It provides full intellisense, type checking, and all language supports from the text editor. A much better DX.

Need Help?

git-logo github issue

x-logo posts

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

ptag-0.1.0.tar.gz (7.3 kB view hashes)

Uploaded Source

Built Distribution

ptag-0.1.0-py3-none-any.whl (8.2 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