pelme / htpy

Generate HTML in Python
http://htpy.dev
MIT License
246 stars 8 forks source link

htpy - HTML in Python

htpy is a library that makes writing HTML in plain Python fun and efficient, without a template language.

Define HTML in Python:

from htpy import body, h1, head, html, li, title, ul

menu = ["egg+bacon", "bacon+spam", "eggs+spam"]

print(
    html[
        head[title["Today's menu"]],
        body[
            h1["Menu"],
            ul(".menu")[(li[item] for item in menu)],
        ],
    ]
)

And Get HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Today's menu</title>
  </head>
  <body>
    <h1>Menu</h1>
    <ul class="menu">
      <li>egg+bacon</li>
      <li>bacon+spam</li>
      <li>eggs+spam</li>
    </ul>
  </body>
</html>

Motivation for This Project

At Personalkollen, where htpy was originally developed we often found ourselves hitting walls when using classic templates. htpy was created to improve the productiveness and experience of generating HTML from a Python backend.

Key Features

Philosophy

htpy generates HTML elements and attributes and provide a few helpers.

htpy does not enforce any particular pattern or style to organize your pages, components and layouts. That does not mean that htpy cannot be used to build sophisticated web pages or applications.

Rather the opposite: you are encouraged the leverage the power of Python to structure your project. Use modules, classes, functions, decorators, list comprehension, generators, conditionals, static typing and any other feature of Python to organize your components. This gives you a lot of power and makes htpy scale from a single small Flask project to bigger applications.

Common patterns can give you some ideas that you can build upon yourself.

The Syntax

Child elements are specified using the [] syntax. This may look strange at first but it has some nice benefits. This clearly separates attributes from child elements and makes the code more readable. It is implemented using the __getitem__ method, just like lists or dicts.

Installation

htpy is available on PyPI. You may install the latest version using pip:

pip install htpy

Documentation

The full documentation is available at htpy.dev: