# Ludic > Ludic lets you write HTML as typed Python components. The type checker validates the markup, so wrong nesting, unknown attributes and missing arguments are caught before a page renders. Ludic only renders HTML, so it fits into Starlette, FastAPI, Django or any other framework, and it pairs with htmx. --- # Introduction > I've just composed my first PageLayout component and I have no words! > > — Igor Davydenko Ludic lets you write HTML as typed Python components. Your type checker validates the markup, so wrong nesting, unknown attributes and missing arguments are caught before a page ever renders. At its core Ludic only renders HTML, so it fits into the web framework you already use, and it pairs naturally with [htmx](https://htmx.org/). ```python from typing import override from ludic import Attrs, Component from ludic.html import a, b, p class LinkAttrs(Attrs): to: str class Link(Component[str, LinkAttrs]): @override def render(self) -> a: return a(*self.children, href=self.attrs["to"]) p(t"Hello {b('Stranger')}! Click {Link('here', to='/home')}.").to_html() #

Hello Stranger! Click here.

``` Invalid markup is a type error. This is what [mypy](https://mypy-lang.org/) reports: ```python br("Hello, World!") # error: Argument 1 to "br" has incompatible type "str"; expected "Never" html(body()) # error: Argument 1 to "html" has incompatible type "body"; expected "head" div("Test", href="test") # error: Unexpected keyword argument "href" for "div" Link("here", too="/home") # error: Unexpected keyword argument "too" for "Link"; did you mean "to"? Link(div("here"), to="/home") # error: Argument 1 to "Link" has incompatible type "div"; expected "str" Link("here") # error: Missing named argument "to" for "Link" ``` ## Features - **Type-guided HTML**: every element knows which children and attributes it allows - **Components** in pure Python, composed like in [React](https://react.dev/) - Mix markup and text with Python 3.14 **t-strings** (template strings) - Text is **escaped by default**, trusted markup is marked explicitly with `Safe` - Typed ** htmx** attributes, so dynamic pages need almost no JavaScript - Works with **Starlette**, **FastAPI** and **Django**, or with no framework at all - Typed CSS for your components with **Themes** - Simple, responsive layouts adopted from the **Every Layout Book** ## Comparison Here is how Ludic compares to other ways of producing HTML in Python: | Feature | Ludic | [htpy](https://htpy.dev/) | [FastHTML](https://fastht.ml/) | [tdom](https://github.com/t-strings/tdom) | [Jinja2](https://jinja.palletsprojects.com/) | |---|---|---|---|---|---| | How you write HTML | Python calls and t-strings | Python calls, children in [] | Python calls | HTML inside t-strings | Template files | | Children and attributes type-checked per element | Yes | No | No | No | No | | Web framework | Optional: Starlette, FastAPI, Django or none | Any | Its own, built on Starlette | Any | Any | | Python | 3.14+ (3.12+ with 0.5.x) | 3.10+ | 3.10+ | 3.14+ | 3.7+ | The others are a better fit in some cases: - **htpy** supports older Python versions and needs no type checker plugin. - **FastHTML** is a complete web framework rather than a library you add to one. - **tdom** lets you write real HTML syntax instead of Python calls. - **Jinja2** keeps templates in files that people who do not write Python can edit. ## Quick Example Here is a simple re-implementation of an example from [Reflex](https://reflex.dev/docs/getting-started/introduction/#an-example:-make-it-count) (although only for natural numbers): The counter can be included on any page like here: ```python from typing import override from ludic.html import b from ludic.web import Endpoint, LudicApp, Request from ludic.catalog.buttons import ButtonDanger, ButtonSuccess from ludic.catalog.layouts import Box, Cluster app = LudicApp() @app.get("/") def index(request: Request) -> Box: return Box(Counter(0)) ``` Note that the `Box` is just a component wrapping the buttons and the number to make it nicely framed. You can read more about the `Box` in the **[Layouts](https://getludic.dev/catalog/layouts)** section later. Anyway, the `Counter` component is the part that is more interesting: ```python @app.get("/counter/{number:int}") def Counter(number: int) -> Cluster: return Cluster( ButtonDanger( "Decrement", disabled=number <= 0, hx_get=app.url_path_for("Counter", number=max(0, number - 1)), hx_target="#counter", ), b(number, style={"font-size": "2em"}), ButtonSuccess( "Increment", hx_get=app.url_path_for("Counter", number=number + 1), hx_target="#counter", ), id="counter", ) ``` ## Requirements Python 3.14+ > **Note** > > : Ludic 0.5.x supports Python 3.12+ with f-strings. For Python 3.12 or 3.13, use Ludic 0.5.x and f-strings instead of t-strings. ## Installation The core package renders HTML and has a single dependency: ``` pip install ludic ``` The following command also installs the web framework built on Starlette, form parsing and code highlighting. If you want to use FastAPI or Django, check the [Other Integrations guide](https://getludic.dev/docs/integrations): ``` pip install "ludic[full]" ``` You can also use the [cookiecutter](https://github.com/cookiecutter/cookiecutter) template to quickly create a new project, using [UV](https://docs.astral.sh/uv/) you can do that with only one command: ``` uvx cookiecutter gh:getludic/template ``` For more information on how to get started, check the [Getting Started guide](https://getludic.dev/docs/getting-started). ### Type Checking Elements from `ludic.html` are checked by plain type hints. To also check the attributes of your own components, enable the mypy plugin in `pyproject.toml`: ```toml [tool.mypy] plugins = ["ludic.mypy_plugin"] ``` ## Integrations Here is a list of integrations and a link to the guide on how to get started: ## Contributing Any contributions to the framework are warmly welcome! Your help will make it a better resource for the community. If you're ready to contribute, read the [contribution guide on GitHub](https://github.com/getludic/ludic/blob/main/CONTRIBUTING.md). - [GitHub Issues](https://github.com/getludic/ludic/issues) – If you encounter a bug, please report it here. - [GitHub Discussions](https://github.com/getludic/ludic/discussions) – To request a new feature, this is the best place to initiate the discussion. - [Discord](https://discord.gg/7nK4zAXAYC) – Join our Discord server for support, sharing ideas, and receiving assistance. Source: https://getludic.dev/docs/ --- # Getting Started The fastest way to get started with a Ludic project is to use the [Cookiecutter template](https://github.com/getludic/template). Follow the steps below to set up your project quickly. > **Note** > > : This guide covers Ludic 1.0 which requires Python 3.14+ and uses t-strings. If you're using Python 3.12 or 3.13, use Ludic 0.5.x with f-strings instead. Install with > > `--python 3.13` > > and use f-strings in your code. ## Installation Steps 1. **Install UV Package Manager**If you don't have UV installed yet, check the official [installation instructions](https://docs.astral.sh/uv/getting-started/installation/). 2. **Generate a Ludic Project**Use the Cookiecutter template to create a new Ludic project. Run the following command in your terminal: ``` uvx cookiecutter gh:getludic/template ``` 3. **Install Dependencies**Navigate to the new project's directory and install the required dependencies using UV: ``` uv sync --python 3.14 ``` 4. **Run the Project**Start your project using Uvicorn with the following command: ``` uv run uvicorn src.main:app --reload ``` 5. **Access the Application**Open your browser and visit [http://localhost:8000](http://localhost:8000) to see your running application. ## Structure The cookiecutter template generates a somewhat opinionated project structure. Feel free to adjust it or suggest a different one on GitHub. Here is the structure: ```bash . ├── src │ ├── __init__.py │ ├── endpoints │ │ ├── __init__.py | | ├── errors.py │ │ ├── index.py │ │ └── ... │ ├── components.py │ ├── main.py │ ├── pages.py │ └── ... ├── static ├── tests ├── README.md └── pyproject.toml ``` For larger applications, the structure can vary significantly. Additionally, many modules are missing, such as models and database connections. However, if you're just beginning, this still serves as a good starting point. #### `pages.py` The idea is to create a few pages (regular components) that render as valid HTML documents using the `` root tag. #### `endpoints` The endpoints module contains all the application's endpoints. The index module includes endpoints that render when users open the site, serving as the root of your web application. The errors module contains error handlers, such as displaying the 404 page. #### `components.py` Any component you want to use in your application should be registered here. For example, a `Navigation` component and its attributes could be registered in the `components.py` file. #### `main.py` The module instantiates the `LudicApp` class and registers routes by importing the `endpoints` module. ## What's Next? In the following sections of this documentation, you will learn more about writing components and endpoints, as well as the various other tools available. You will also learn about the Catalog, which can be used to quickly create the basic layout of your web application. Source: https://getludic.dev/docs/getting-started --- # Components In Ludic, you can create components similar to React components. These components don't have anything like a state similar to React, but they do consist of children and attributes. ## Key Concepts - **Components**: a component is a reusable chunk of code that defines a piece of your user interface. Think of it like a blueprint for an HTML element, but more powerful. - **Elements**: these represent the individual HTML tags (like ``, `
`, `

`, etc.) that make up the structure of your page. - **Attributes**: These help define the properties on your components and elements. They let you modify things like a link's destination, text color, or an element's size. - **Hierarchy**: Components can contain other components or elements, creating a tree-like structure. - **Types**: A safety net to help you write correct code, preventing errors just like making sure LEGO pieces fit together properly. ## Types of Components - **Regular**: These are flexible, letting you have multiple children of any type. - **Strict**: Perfect for when you need precise control over the structure of your component – like a table where you must have a head and a body. ## Regular Components Let's break down a simplified version of the `Link` component: ```python from typing import override from ludic import Attrs, Component class LinkAttrs(Attrs): to: str class Link(Component[str, LinkAttrs]): @override def render(self): return a( *self.children, href=self.attrs["to"], style={"color": "#abc"}, ) ``` - *HTML Rendering*: This component renders as the following HTML element: - `...` - *Type Hints*: `Component[str, LinkAttrs]` provides type safety: - *str*: Enforces that all children of the component must be strings - *LinkAttrs*: Ensures the required to attribute is present - *Attributes*: `LinkAttrs` inherits from `Attrs`, which is a `TypedDict` (a dictionary with defined types for its keys) The component would be instantiated like this: ```python Link("here", to="https://example.org") ``` Static type checkers will validate that you're providing the correct arguments and their types. ### Multiple Children The current definition doesn't strictly enforce a single child. This means you could technically pass multiple strings (`Link("a", "b")`). To create a stricter component, inherit from `ComponentStrict`: This subclass of Component allows for finer control over children. More about this in the next section. ## Strict Components Strict components offer more precise control over the types and structures of their children compared to regular components. Let's illustrate this with a simplified `Table` component: ```python from ludic.attrs import GlobalAttrs from ludic.html import thead, tbody, tr class TableHead(ComponentStrict[tr, GlobalAttrs]): @override def render(self) -> thead: return thead(*self.children, **self.attrs) class TableBody(ComponentStrict[*tuple[tr, ...], GlobalAttrs]): @override def render(self) -> tbody: return tbody(*self.children, **self.attrs) class Table(ComponentStrict[TableHead, TableBody, GlobalAttrs]): @override def render(self) -> table: return table( self.children[0], self.children[1], **self.attrs, ) ``` **Explanation** - *Strictness*: The `ComponentStrict` class allows you to enforce the exact types and order of children. - *Table Structure*: - `Table`: Expects precisely two children: a `TableHead` followed by a `TableBody`. - `TableHead`: Accepts only a single `tr` (table row) element as its child. - `TableBody`: Accepts a variable number of `tr` elements as children. - *Type Hints*: The `*tuple[tr, ...]` syntax indicates that `TableBody` accepts zero or more tr elements. **Valid Usage (Passes Type Checking)** ```python Table( TableHead(tr(...)), # Table head with a single row TableBody(tr(...), tr(...)) # Table body with multiple rows ) ``` **Key Benefits** - *Enforce Structure*: Prevent incorrect usage that could break your component's layout or functionality. - *Type Safety*: Static type checkers ensure you're building valid component hierarchies. ## Attributes To ensure type safety and clarity, define your component attributes using a subclass of the `Attrs` class. Here's how: ```python from typing import NotRequired from ludic.attrs import Attrs class PersonAttrs(Attrs): id: str name: str is_active: NotRequired[bool] ``` **Understanding `Attrs` and `TypedDict`** - The `Attrs` class is built upon Python's `TypedDict` concept (see [PEP-589](https://peps.python.org/pep-0589/)) for details). This provides type hints for dictionary-like data structures. ### Controlling Required Attributes In the above case, all attributes except for {Code('is_active')} are required. If you want to make all attributes NOT required by default, you can pass the `total=False` keyword argument to the class definition: ```python from typing import Required from ludic.attrs import Attrs class PersonAttrs(Attrs, total=False): id: Required[str] name: str is_active: bool ``` In this case, all attributes are optional except for the `id` attribute. > **The `Attrs` declaration is an information for type checkers** > > The > > `Attrs` > > class just provides typing information for static type checkers. Your code will work even if you pass key-word arguments to components without declaring them first. All attributes can also subclass from other classes, for example, you can extend the attributes for the ` ``` ### Using t-strings In Ludic, t-strings offer a bit more readable way to construct component content, especially if you need to do a lot of formatting with ``, ``, and other elements for improving typography. Let's modify the previous example using t-strings: ```python p1 = p(t"click {Link("here", to="https://example.com")}") p2 = p("click ", Link("here", to="https://example.com")) assert p1 == p2 # Identical components ``` A t-string keeps its interpolated values as objects. Elements stay elements, and any other value is escaped like a regular string: ```python name = "" p(t"Hello {name}, welcome {b("back")}!").to_html() '

Hello <script>alert(1)</script>, welcome back!

' ``` > **Use t-strings, not f-strings** > > An f-string turns an element into text before Ludic can see it, so the markup ends up escaped on the page. ```python p(f"click {b("here")}").to_html() '

click <b>here</b>

' ``` > **Ludic 0.5.x** > > Ludic 0.5.x for Python 3.12 and 3.13 uses f-strings for the same purpose. They keep the elements in a temporary dictionary, which is cleared automatically in request handlers of the Ludic Web Framework. Anywhere else, wrap the code in > > `with BaseElement.formatter:` > > to avoid leaking memory. None of this applies to t-strings. ## Available Methods All components (and elements too) inherit the following properties and methods from the `BaseElement` class: - `BaseElement` - `children` – children of the component - `attrs` – a dictionary containing attributes - `to_html()` – converts the component to an HTML document - `to_string()` – converts the component to a string representation of the tree - `attrs_for(...)` – filter attributes to return only those valid for a given element or component - `has_attributes()` – whether the component has any attributes - `is_simple()` – whether the component contains one primitive child - `render()` (*abstract method*) – render the component ## Types and Helpers The following is a list of all the other parts that can be used to type and build your application. #### `ludic.elements` - `Element` – base for HTML elements - `ElementStrict` – base for strict HTML elements - `Blank` – represents a blank component which is not rendered, only its children #### `ludic.components` - `Component` – abstract class for components - `ComponentStrict` – abstract class for strict components - `Block` – component rendering as a div - `Inline` – component rendering as a span #### `ludic.types` - `NoChildren` – Makes a component accept no children - `PrimitiveChildren` – Makes a component accept only `str`, `int`, `float` or `bool` - `ComplexChildren` – Makes a component accept only non-primitive types - `AnyChildren` – Makes a component accept any children types - `TAttrs` – type variable for attributes - `TChildren` – type variable for children of components - `TChildrenArgs` – type variable for children of strict components - `Attrs` – base for attributes - `Safe` – marker for a safe string which is not escaped - `JavaScript` – a marker for javascript, subclasses `Safe` #### `ludic.styles` - `GlobalStyles` – type for HTML classes and their CSS properties - `CSSProperties` – type for CSS properties only Source: https://getludic.dev/docs/components --- # Styles and Themes There are two main ways of how to change the look and feel of your apps built with the Ludic framework: - CSS Styling – you can apply custom styles to your components. - Themes – you can change the colors, widths, fonts, etc. of your components. ## CSS Styling There are three primary ways to apply CSS properties to components within your application: 1. The `style` HTML Attribute 2. The `styles` Class Property 3. The `style` HTML Element ### The `style` HTML Attribute You can directly embed styles within an HTML element using the `style` attribute. Here's an example: ```python from ludic.css import CSSProperties from ludic.html import form form(..., style=CSSProperties(color="#fff")) ``` - The `CSSProperties` class is a `TypedDict` for convenience since type checkers can highlight unknown or incorrect usage. - You can also use a regular Python dictionary, which might be better in most cases since CSS properties often contain hyphens: ```python form(..., style={"background-color": "#fff"}) ``` Note that you probably want to specify the color using a theme as you can read more about bellow. ```python form(..., style={"background-color": theme.colors.white}) ``` ### The `styles` Class Property Define CSS properties within your component using the `styles` class property. Example: ```python from typing import override from ludic.attrs import ButtonAttrs from ludic.html import button from ludic.components import ComponentStrict class Button(ComponentStrict[str, ButtonAttrs]): classes = ["btn"] styles = { "button.btn": { "background-color": "#fab", "font-size": "16px", } } @override def render(self) -> button: return button(self.children[0], **self.attrs_for(button)) ``` > **Notice the `classes` attribute** > > The > > `classes` > > attribute contains the list of classes that will > > be applied to the component when rendered (they will be appended if > > there are any other classes specified by the > > `class_` > > attribute). In this case, you need to make sure you collect and render the styles. See Collecting The Styles and Integration In a Page Component. It is also possible to nest styles similar to how you would nest them in SCSS. The only problem is that you might get typing errors if you are using `mypy` or `pyright`: ```python class Button(ComponentStrict[str, ButtonAttrs]): classes = ["btn"] styles = { "button.btn": { "color": "#eee", # type: ignore[dict-item] ".icon": { "font-size": "16px", } } } ... ``` Again, you probably want to use *themes* to assign colors (we'll talk about *themes* later): ```python from ludic.html import style class Button(ComponentStrict[str, ButtonAttrs]): classes = ["btn"] styles = style.use(lambda theme:{ "button.btn": { "color": theme.colors.primary, } }) ... ``` #### Collecting The Styles - **Load Styles:**Use the `style.load()` method to gather styles from all components in your project. This generates a ` ``` - **Targeted Loading:**For more control, use `style.from_components(...)` to load styles from specific components: ```python from ludic.html import style from your_app.components import Button, Form styles = style.from_components(Button, Form) ``` #### Integration In a Page Component You need to load the styles and render them in an HTML document. There are two options how to do that: 1. Use the `ludic.catalog.pages.HtmlPage` component which loads the styles automatically. 2. Create a new *Page* component and use the `style.load()` method manually. The first method is described in the [catalog section](https://getludic.dev/catalog/#htmlpage-component) of the documentation. Here is the second method: ```python from typing import override from ludic.attrs import NoAttrs from ludic.html import html, head, body, style from ludic.components import Component from ludic.types import AnyChildren class Page(Component[AnyChildren, NoAttrs]): @override def render(self) -> html: return html( head( style.load(cache=True) ), body( ... ), ) ``` #### Caching The Styles As mentioned before, passing `cache=True` to `style.load` caches loaded elements' styles during the first render. The problem is that the first request to your application renders the styles without the cache, so the response is a bit slower. If you want to cache the styles before your component even renders for the first time, you can use the `lifespan` argument of the `LudicApp` class: ```python from collections.abc import AsyncIterator from contextlib import asynccontextmanager from ludic.web import LudicApp @asynccontextmanager async def lifespan(_: LudicApp) -> AsyncIterator[None]: style.load(cache=True) # cache styles before accepting requests yield app = LudicApp(lifespan=lifespan) ``` You can read more about `Lifespan` in [Starlette's documentation](https://www.starlette.io/lifespan/). ### The `style` HTML Element You can also directly embed styles within a `Page` component using the `style` element. Here's an example: ```python from ludic.html import style style( { "a": { "text-decoration": "none", "color": "red", }, "a:hover": { "color": "blue", "text-decoration": "underline", }, } ) ``` It is also possible to pass raw CSS styles as a string: ```python from ludic.html import style style(""" .button { padding: 3px 10px; font-size: 12px; border-radius: 3px; border: 1px solid #e1e4e8; } """) ``` ## Themes You can think of themes as an option to create CSS variables, but with typing support and more flexibility. Ludic has two built-in themes: - `ludic.styles.themes.LightTheme` – the default theme. - `ludic.styles.themes.DarkTheme` – the dark theme. ### How to Style Components Using Themes Themes provide a centralized way to manage the look and feel of your components. You can directly access a component's theme to customize its styling based on your theme's settings. Here's a breakdown of how this works: - **Theme Definition:**A theme holds predefined styles like colors, fonts, and spacing. You usually define your theme separately. - **Accessing the Theme:**Components can access the current theme through a special `theme` attribute. This gives you direct access to your theme's values. - **Switching Theme:**Components can switch to a different theme by passing the componentto the `theme.use()` method. You can also switch theme globally. ### Theme Definition You have two options how to create a new theme: 1. subclass `Theme` base class and define the theme's attributes 2. instantiate an existing theme and override its attributes Here is an example of the first approach: ```python from dataclasses import dataclass from ludic.styles.types import Color from ludic.styles.themes import Colors, Fonts, Theme @dataclass class MyTheme(Theme): name: str = "my-theme" fonts: Fonts = field(default_factory=Fonts) colors: Colors = field( default_factory=lambda: Colors( primary=Color("#c2e7fd"), secondary=Color("#fefefe"), success=Color("#c9ffad"), info=Color("#fff080"), warning=Color("#ffc280"), danger=Color("#ffaca1"), light=Color("#f8f8f8"), dark=Color("#414549"), ) ) ``` You can also instantiate an existing theme and override its attributes: ```python from ludic.styles.themes import Fonts, Size, LightTheme theme = LightTheme(fonts=Fonts(serif="serif", size=Size(1, "em"))) ``` ### Accessing The Theme There are two ways to access the theme: 1. use the component's `theme` attribute 2. call `style.use(lambda theme: { ... })` on the component's `styles` class attribute Here is an example combining both approaches: ```python from typing import override from ludic.attrs import ButtonAttrs from ludic.components import Component from ludic.html import button, style class Button(Component[str, ButtonAttrs]): classes = ["btn"] styles = style.use(lambda theme: { "button.btn:hover": { "background-color": theme.colors.primary.lighten(1) } }) @override def render(self) -> button: return button( *self.children, style={ # Use primary color from theme "background-color": self.theme.colors.primary } ) ``` ### Switching Theme You can switch the theme globally or for a specific component: 1. use the `theme.use()` method to switch theme in a component 2. use the `set_default_theme()` method to switch theme globally 3. use the `style.load()` to render styles from loaded components with a different theme Here are some examples: ```python from ludic.attrs import GlobalAttrs from ludic.styles.themes import DarkTheme, LightTheme, set_default_theme from ludic.components import Component from ludic.html import a, b, div, style dark = DarkTheme() light = LightTheme() set_default_theme(light) class MyComponent(Component[str, GlobalAttrs]): styles = style.use( # uses the theme specified by the `style.load(theme)` method # or the default theme if `style.load()` was called without a theme lambda theme: { "#c1 a": {"color": theme.colors.warning}, } ) @override def render(self) -> div: return div( # uses the local theme (dark) dark.use(ButtonPrimary("Send")), # uses the default theme (light) ButtonSecondary("Cancel"), # uses the default theme (light) style={"background-color": self.theme.colors.primary} ) # loads styles form all components with the default theme (light) my_styles = style.load() # loads style with the specified theme (dark) my_styles = style.load(theme=dark) ``` Source: https://getludic.dev/docs/styles --- # Using HTMX with Ludic [HTMX](https://htmx.org) is a powerful library that simplifies the creation of dynamic, interactive web pages. It lets you achieve the responsiveness of single-page applications without the complexity of writing extensive JavaScript code. HTMX works by extending standard HTML with special attributes that control how elements interact with the server. The most typical example is when you want to fetch content from a server on a button click event and append or replace content on your page with the response. You can examine a similar example bellow. Here is a couple of HTMX attributes that allow you to add dynamic functionality to your pages: - `hx-get` – issues a GET request to the server - `hx-post` – issues a POST request to the server - `hx-target` – specifies which element is replaced by the response - `hx-select` – specifies which element from the response is replaces - `hx-swap` – controls how content is swapped - `hx-trigger` – specifies which event triggers the request > **HTMX Attributes Reference** > > Check all the available attributes in the > > [HTMX documentation](https://htmx.org/reference/) > > . ## HTMX Integration in Ludic The `ludic.html` module seamlessly supports HTMX attributes, making it easy to add dynamic functionality to your pages. Let's see a simple example: ```python from ludic.html import button button("Click Me", hx_post="/clicked", hx_swap="innerHTML") ``` This code would generate the following HTML: ```html ``` Please note that HTMX uses a special attribute, `hx-on*`, which cannot currently be type-checked. However, it can still be used in the following way: ```python button( "Get Info!", hx_get="/info", hx_on__before_request="alert('Alert!')", # type: ignore[call-arg] ) ``` This would render the attribute as `hx-on--before-request`which is [fine with htmx](https://htmx.org/attributes/hx-on/). ## Setting up an HTMX-Enabled Page 1. **Include the HTMX library**: Add the HTMX script to your base HTML component ```python from typing import override from ludic.attrs import NoAttrs from ludic.catalog.pages import HtmlPage, Head, Body from ludic.components import Component from ludic.types import AnyChildren class Page(Component[AnyChildren, NoAttrs]): @override def render(self) -> HtmlPage: return HtmlPage( Head(title="My App"), Body(*self.children, htmx_version="2.0.11"), ) ``` 2. **Use the `Page` component**: Employ the Page component as the foundation for your HTML documents to ensure they load the necessary HTMX script. > **Default `hx-swap` Operation** > > The default HTMX swap operation is set to > > `outerHTML` > > in all pages based on the > > `HtmlPage` > > component. This is different than HTMX default which is > > `innerHTML` > > . ## Sample Swap Operation Let's illustrate how to create a dynamic page with HTMX and Ludic: ```python from ludic.html import b, div, p, button from ludic.web import LudicApp, Request from your_app.pages import Page app = LudicApp() @app.get("/") def homepage(request: Request) -> Page: return Page( p( "This is a simple example with one button performing the " "hx-swap operation." ), button("Show Hidden Content", hx_get=request.url_for(content).path), ) @app.get("/content") def content() -> p: return p(b("This is the hidden content.")) ``` You can test the performed action here: ### Explanation - **Button Behavior**: Clicking the button triggers an HTTP GET request to `/content`. The response replaces the original button with the content returned from the `/content` endpoint. - **Web Framework**: Ludic acts as a web framework (built on [Starlette](https://www.starlette.io/)), empowering you to define endpoints and handle requests. Explore the [Web Framework](https://getludic.dev/docs/web-framework) section of the documentation for in-depth information. ## Headers It is possible to append custom HTMX headers in responses, here is an example: ```python from ludic import types from ludic.html import p from your_app.server import app @app.get("/") def index() -> tuple[p, types.HXHeaders]: return p("Example"), {"HX-Location": {"path": "/", "target": "#test"}} ``` You can also change the return type of your endpoint with `tuple[div, types.Headers]` which allows arbitrary headers, not just HTMX-specific ones. ## Rendering JavaScript In some cases, HTMX components require some JavaScript code. For that purpose, there is the `ludic.types.JavaScript` class: ```python from ludic.html import button, div, h2, table from ludic.types import JavaScript from your_app.server import app @app.get("/data") def data() -> div: return div( h2("Data"), table(...), button("Click Here", on_click=JavaScript("alert('test')")), ) ``` Source: https://getludic.dev/docs/htmx --- # Web Framework The Ludic library provides wrappers around [Starlette](https://www.starlette.io/) framework to make it easy to write asynchronous web applications based on HTMX and Ludic Components. Ludic includes an application class `LudicApp` that tight together all other functionality. Here is how you can create an instance of the class: ```python from ludic.web import LudicApp app = LudicApp() ``` The `LudicApp` class supports the same parameters as the `Starlette` class from the *Starlette* framework. ## Routing To register handlers in your app, you can use the `routes` arguments of the `LudicApp` class like this: ```python from ludic.web import LudicApp, Request from ludic.web.routing import Route def homepage(request: Request) -> p: return p("Hello, world!") routes = [ Route("/", homepage), ] app = LudicApp(debug=True, routes=routes) ``` Alternatively, you can use a method decorator to register an endpoint: ```python from ludic.web import LudicApp, Request from ludic.web.routing import Route app = LudicApp(debug=True) @app.get("/") def homepage(request: Request) -> p: return p("Hello, world!") ``` ### The Application Instance *class* `ludic.app.LudicApp`*(debug=False, routes=None, middleware=None, exception_handlers=None, on_startup=None, on_shutdown=None, lifespan=None)* Creates an application instance. #### Parameters The list of parameters can be found in the [Starlette documentation](https://www.starlette.io/applications/#instantiating-the-application). #### Methods - `app.register_route`*(path: str, method: str = "GET")* – decorator to register function based endpoint handler - `app.get`*(path: str, **kwargs: Any)* – decorator to register function endpoint handling GET HTTP method - `app.post`*(path: str, **kwargs: Any)* – decorator to register function endpoint handling POST HTTP method - `app.put`*(path: str, **kwargs: Any)* – decorator to register function endpoint handling PUT HTTP method - `app.patch`*(path: str, **kwargs: Any)* – decorator to register function endpoint handling PATCH HTTP method - `app.delete`*(path: str, **kwargs: Any)* – decorator to register function endpoint handling DELETE HTTP method - `app.endpoint`*(path: str)* – decorator to register component based endpoint - `app.add_route`*(path: str, route: Callable[..., Any], method: str, **kwargs: Any)* – register any endpoint handler - `app.url_path_for`*(name: str, /, **path_params: Any)* – get URL path for endpoint of given name - `app.exception_handler`*(exc_class_or_status_code: int | type[Exception])* – register exception handler ## Endpoints There are three types of endpoints that you can create: - Function-Based - Component-Based ### Function-Based These are functions returning Ludic components, a tuple or the [Starlette's Response class](https://www.starlette.io/responses/). Here are some examples of function handlers registered in Ludic: ```python from ludic.web.datastructures import FormData from ludic.web.exceptions import NotFoundError from your_app.database import db from your_app.pages import Page from your_app.models import Person from your_app.components import Header @app.get("/people/{id}") async def show_person(id: str) -> Page: person: Person = db.people.get(id) if person is None: raise NotFoundError("Contact not found") return Page( Header(person.name), ... ) @app.post("/people/") async def register_person(data: FormData) -> Page: person: Person = Person.objects.create(**data) return await show_person(person.id), 202 ``` ### Component-Based While it is possible to use function-based handlers everywhere, in the case of HTMX-based web applications, we want to also create a lot of endpoints rendering only sole form elements, tables, and so on. We don't need to always return the whole HTML document in `` tag. We could use function-based handlers for that, however, it is often better to think of endpoints as just another components. Component-based endpoints can only have one generic argument which is the type of attributes. They cannot have children. Here is an example where we create two component-based endpoints: ```python from ludic.web import Endpoint from ludic.web.datastructures import FormData from your_app.database import db from your_app.pages import Page from your_app.models import Person from your_app.components import Header, Body @app.get("/") async def index() -> Page: return Page( Header("Click To Edit"), Body(*[ await Contact.get(contact_id) for contact_id in db.contacts ]), ) @app.endpoint("/contacts/{id}") class Contact(Endpoint[ContactAttrs]): @classmethod async def get(cls, id: str) -> Self: contact = db.contacts.get(id) return cls(**contact.as_dict()) @classmethod async def put(cls, id: str, data: FormData) -> Self: contact = db.contacts.get(id) contact.update(**data) return await cls.get(id) @override def render(self) -> div: return div( Pairs(items=self.attrs.items()), ButtonPrimary( "Click To Edit", hx_get=self.url_for(ContactForm).path, ), hx_target="this", ) @app.endpoint("/contacts/{id}/form/") class ContactForm(Endpoint[ContactAttrs]): @classmethod async def get(cls, id: str) -> Self: contact = db.contacts.get(id) return cls(**contact.as_dict()) @override def render(self) -> Form: return Form( # ... form fields definition here ..., ButtonPrimary("Submit"), ButtonDanger("Cancel", hx_get=self.url_for(Contact).path), hx_put=self.url_for(Contact).path, hx_target="this", ) ``` One benefit of this approach is that you can create components that generate the URL path for other component-based endpoints with the `url_for` method. More about that in the next section. ### Reverse URL Lookups There are two possible ways to generate the URL for a particular route handled by an endpoint: - `Request.url_for` - `Endpoint.url_for` **`Request.url_for(endpoint: Callable[..., Any] | str, ...)`** This method is available on the `ludic.web.requests.Request` object. It generates and `URLPath` object for a given endpoint. > **Host header poisoning** > > `Request.url_for(...)` returns an *absolute* URL whose scheme and host are derived from the incoming request – ultimately from the HTTP `Host` header (and `X-Forwarded-*` headers when proxy headers are trusted). If your app accepts requests with an untrusted `Host`, an attacker can poison every absolute URL you render – including `hx-get` / `hx-post` attributes, links, redirects, and links sent in outbound messages – pointing the browser at an attacker-controlled domain. > > Mitigations: > > - Prefer `request.url_path_for(...)` – or `request.url_for(...).path` – for in-app links and HTMX attributes. Relative paths cannot be poisoned and are usually what you want anyway. > - Install `starlette.middleware.trustedhost.TrustedHostMiddleware` with an explicit `allowed_hosts` list so the app rejects requests with a forged `Host` header before any handler runs. > - Behind a reverse proxy or CDN, configure `ProxyHeadersMiddleware` (or an equivalent) with a trusted-proxy allowlist so `X-Forwarded-Host` / `X-Forwarded-Proto` are only honored from your own infrastructure. > > FastAPI users get the same exposure: the FastAPI integration wraps the incoming request in Ludic's `Request`, so `Request.url_for(...)` is reachable from FastAPI handlers and the same advice applies. **`Endpoint.url_for(endpoint: type[RoutedProtocol] | str, ...)`** This method is available on a component-based endpoint. It has one small advantage over the `request`'s method – if the destination component defines the same attributes, the path parameters are automatically extracted so you don't need to pass them via key-word arguments. Here are examples: - `ContactForm(...).url_for(Contact)` – Even though the `ContactForm` endpoint requires the `id` path parameter, it is automatically extracted from `ContactForm(...).attrs` since the `ContactForm` and `Contact` share the same attributes – `ContactAttrs`. - If these attribute types are not equal, you need to specify the URL path parameter explicitly, e.g. `ContactForm(...).url_for(Foo, id=self.attrs["foo_id"])`. - If the first argument to `url_for` is the name of the endpoint, you need to always specify the URL path parameters explicitly. ### Handler Responses Your handler is not required to return only a valid element or component, you can also modify headers, status code, or return a `JSONResponse`: ```python from ludic import types from ludic.html import div @app.get("/") def index() -> tuple[div, types.Headers]: return div("Headers Example"), {"Content-Type": "..."} ``` When it comes to the handler's return type, you have the following options: - `BaseElement` – any element or component - `tuple[BaseElement, int]` – any element or component and a status code - `tuple[BaseElement, types.Headers]` – any element or component and headers as a dict - `tuple[BaseElement, int, types.Headers]` – any element or component, status code, and headers - `starlette.responses.Response` – valid Starlette `Response` object ### Handler Arguments Here is a list of arguments that your handlers can optionally define (they need to be correctly type-annotated): - `: ` if the endpoint accepts path parameters, they can be specified in the handler's arguments - `request: Request` the Ludic's slightly modified `ludic.web.requests.Request` class based on [Starlette's one](https://www.starlette.io/requests/) - `params: QueryParams` contain query string parameters and can be imported from `ludic.web.datastructures.QueryParams` - `data: FormData` an immutable multi-dict, containing both file uploads and text input from form submission - `headers: Headers` HTTP headers exposed as an immutable, case-insensitive, multi-dict ## Parsers > **Experimental** > > This module is in an experimental state. The API may change in the future. The `ludic.parsers` module contains helpers for parsing `FormData`. The way it works is that you define `Attrs` class with `Annotated` arguments like here: ```python class PersonAttrs(Attrs): id: NotRequired[int] name: Annotated[str, parse_name] email: Annotated[str, parse_email] ``` Now you can use the `Parser` class to annotate arguments of your handler. The parser will attempt to parse form data if any `Callable` is found in the metadata argument of `Annotated`: ```python from ludic.web.parsers import Parser @app.put("/people/{id}") async def update_person(cls, id: str, data: Parser[PersonAttrs]) -> div: person = db.people.get(id) person.update(data.validate()) return div(...) # return updated person ``` The `Parser.validate()` uses [typeguard](https://typeguard.readthedocs.io/) to validate the form data. If the validation fails, the method raises `ludic.parsers.ValidationError` if the request's form data are not valid. If unhandled, this results in `403` status code. ### Parsing Collections You can also use the `ListParser` class to parse a list of data. It parses form data in a way similar to the `Parser` class, however, it expects the form data to have the identifier column as key. For example, we want to parse a first and last name columns from a list of people, here are the example form data the `ListParser` is able to handle: ``` first_name:id:1=Joe& first_name:id:2=Jane& last_name:id:1=Smith& last_name:id:2=Doe ``` This would be transformed in the following structure: ```python [ {"id": 1, "first_name": "Joe", "last_name": "Smith"}, {"id": 2, "first_name": "Jane", "last_name": "Doe"}, ] ``` This is how you could use the `ListParser` to parse a list of this kind of data from your view: ```python from ludic.web.parsers import ListParser @app.put("/people/") async def update_people(cls, id: str, data: ListParser[PersonAttrs]) -> div: people.update(data.validate()) return div(...) # return updated people ``` ## Error Handlers You can use error handlers for custom pages for non-ok HTTP status codes. You can register a handler with the `app.exception_handler` decorator: ```python from your_app.pages import Page @app.exception_handler(404) async def not_found() -> Page: return Page( Header("Page Not Found"), Body(Paragraph("The page you are looking for was not found.")), ) @app.exception_handler(500) async def server_error() -> Page: return Page( Header("Server Error"), Body(Paragraph("Server encountered an error during processing.")), ) ``` Optionally, you can use the `request: Request` and `exc: Exception` arguments for the handler: ```python @app.exception_handler(500) async def server_error(request: Request, exc: Exception) -> Page: ... ``` ## Exceptions The `ludic.web.exceptions` contains a lot of useful exceptions that can be raised in your views and caught in your custom error handlers: - `ClientError(HTTPException)` – default status code `400` - `BadRequestError(ClientError)` – default status code `400` - `UnauthorizedError(ClientError)` – default status code `401` - `PaymentRequiredError(ClientError)` – default status code `402` - `ForbiddenError(ClientError)` – default status code `403` - `NotFoundError(ClientError)` – default status code `404` - `MethodNotAllowedError(ClientError)` – default status code `405` - `TooManyRequestsError(ClientError)` – default status code `429` - `ServerError(HTTPException)` – default status code `500` - `InternalServerError(ServerError)` – default status code `500` - `NotImplementedError(ServerError)` – default status code `501` - `BadGatewayError(ServerError)` – default status code `502` - `ServiceUnavailableError(ServerError)` – default status code `503` - `GatewayTimeoutError(ServerError)` – default status code `504` ## WebSockets WebSockets support is not yet fully tested in Ludic. However, Starlette has good support for WebSockets so it should be possible to use Ludic as well. ## Testing Testing Ludic Web Apps is the same as testing Starlette apps which use a `TestClient` class exposing the same interface as `httpx` library. Read more about testing in the [Starlette documentation](https://www.starlette.io/testclient/). Source: https://getludic.dev/docs/web-framework --- # Other Integrations This guide will walk you through the process of integrating the Ludic framework with other projects (aside from Starlette integration, which is covered in the [Web Framework](https://getludic.dev/docs/web-framework) section of the documentation). Here is the list of currently supported integrations: - FastAPI - Django ## FastAPI This guide will walk you through integrating the Ludic framework with a FastAPI project. We will cover the necessary setup steps and provide examples of how to use Ludic in your FastAPI application. ### Installation To install Ludic with FastAPI support, use the following command: ```sh pip install "ludic[fastapi]" ``` ### Setup Integrating Ludic with `FastAPI` is straightforward. Simply configure the `LudicRoute` route class: ```python from fastapi import FastAPI from ludic.contrib.fastapi import LudicRoute app = FastAPI() app.router.route_class = LudicRoute ``` ### Creating Endpoints with Ludic You can return Ludic components directly from FastAPI endpoints: ```python from fastapi import FastAPI from ludic.html import html, head, body, div, h1, p, title, b from ludic.contrib.fastapi import LudicRoute app = FastAPI() app.router.route_class = LudicRoute @app.get("/") def index() -> html: return html( head(title("My Page")), body( div( h1("My Homepage"), p(t"Hello {b('World!')}"), id="container", ) ) ) ``` ### Using Predefined Components You can also use predefined components from Ludic's catalog: ```python import json from fastapi import FastAPI, Request from ludic.catalog.pages import HtmlPage, Head, Body from ludic.catalog.headers import H1 from ludic.catalog.typography import Code, CodeBlock, Link, Paragraph from ludic.catalog.layouts import Center, Stack from ludic.components import Component from ludic.types import AnyChildren from ludic.contrib.fastapi import LudicRoute app = FastAPI() app.router.route_class = LudicRoute class MyPage(Component[AnyChildren, GlobalAttrs]): def render(self) -> HtmlPage: return HtmlPage( Head(title="My Page"), Body( Center( Stack(*self.children, **self.attrs), style={"padding-block": "xxl"}, ), htmx_version="2.0.11", ), ) @app.get("/") async def index_with_components(request: Request) -> MyPage: query_params = dict(request.query_params) return MyPage( H1("Demo Using The Catalog"), Paragraph( t"This page is using components from " t"{Link('Ludic framework.', to='https://getludic.dev')}" ), Paragraph(t"Here is the content of {Code('request.query_params')}"), CodeBlock(json.dumps(query_params, indent=4), language="json"), ) ``` ### Manual Response Handling If you need more control, use `LudicResponse` explicitly: ```python from fastapi import FastAPI from ludic.html import p from ludic.contrib.fastapi import LudicResponse, LudicRoute app = FastAPI() app.router.route_class = LudicRoute @app.get("/custom") def custom_response() -> LudicResponse: return LudicResponse( p("Hello, World!"), status_code=201, headers={"X-Custom-Header": "Ludic"} ) ``` ### Example You can check a working FastAPI example: - [in the examples section](https://getludic.dev/examples/cascading-selects) - [source code on GitHub](https://github.com/getludic/ludic/blob/main/examples/fastapi_example.py) ## Django This guide wil walk you through integration of the Ludic framework with a Django project. We will cover the necessary setup steps, how to configure middleware, and provide examples of how to use Ludic in your Django views. ### Installation First, you need to install Ludic. You can do this using pip: ``` pip install "ludic[django]" ``` ### Middleware Configuration To use Ludic with Django, you need to add the Ludic middleware to your Django settings. This middleware helps manage the Ludic elements during the request-response cycle, clean up cache, and so on. 1. Open your `settings.py` file. 2. Add `LudicMiddleware` to the `MIDDLEWARE` list: ```python MIDDLEWARE = [ # other middlewares... "ludic.contrib.django.LudicMiddleware", ] ``` ### Creating Views with Ludic Let's create a simple HTML page using Ludic elements in a Django view. Here is the content of the `views.py` file rendering a valid HTML page: ```python from django.http import HttpRequest from ludic.contrib.django import LudicResponse from ludic.html import html, head, body, div, h1, p, title, b def index(request: HttpRequest) -> LudicResponse: return LudicResponse( html( head( title("My Page"), ), body( div( h1("My Homepage"), p(t"Hello {b("World!")}"), id="container", ) ) ) ) ``` However, you are not limited to `ludic.html` module. You can build your own [components](https://getludic.dev/docs/components) or use the ones available in the [catalog](https://getludic.dev/catalog/). Here is a simple example creating a page component and using it in a view: ```python import json from django.http import HttpRequest from ludic.attrs import GlobalAttrs from ludic.catalog.layouts import Center, Stack from ludic.catalog.pages import HtmlPage, Head, Body from ludic.catalog.headers import H1 from ludic.catalog.typography import Code, CodeBlock, Link, Paragraph from ludic.components import Component from ludic.contrib.django import LudicResponse from ludic.types import AnyChildren class MyPage(Component[AnyChildren, GlobalAttrs]): def render(self) -> HtmlPage: return HtmlPage( Head(title="My Page"), Body( Center( Stack(*self.children, **self.attrs), style={"padding-block": self.theme.sizes.xxl}, ), htmx_version="2.0.11", ), ) def index_with_components(request: HttpRequest) -> LudicResponse: return LudicResponse( MyPage( H1("Demo Using The Catalog"), Paragraph( t"This page is using components from " t"{Link("Ludic framework.", to="https://getludic.dev")}" ), Paragraph(t"Here is the content of {Code("request.GET")}:"), CodeBlock( json.dumps(request.GET.dict(), indent=4), language="json", ), ) ) ``` > ****Note about `LudicResponse`**** > > If you keep the > > `LudicMiddleware` > > in the > > `MIDDLEWARE` > > variable as the last, you can directly return Ludic components in your views, without wrapping them in the > > `LudicResponse` > > class. Source: https://getludic.dev/docs/integrations --- # Catalog The `ludic.catalog` module is a collection of components designed to help build applications using the Ludic framework. It serves as both a resource for building new web applications and also as a showcase of ways to implement components. Each item in the catalog is a reusable component that generates HTML code and registers its own CSS styles.. The registered CSS are loaded using the `style.load()` method, as detailed in the [Styles and Themes](https://getludic.dev/docs/styles) section of the documentation. The catalog components are like **Lego pieces** you can assemble together to build interactive and beautiful **HTML documents** with **minimalistic** approach: - You write HTML in pure Python, this removes any need for template engines and offers type safety as a bonus. - The generated CSS is simple, extensible, and easy to understand. The layouts you can use for building your pages are responsive, reusable, and robust. They are based on the amazing [Every Layout Book](https://every-layout.dev/). ## How Do You Use The Catalog? In order for everything to work correctly, the first thing you usually need to do is to create a `Page` component. This component is important for two reasons: - It renders as a valid HTML document with (optionally) HTMX script loaded; - It renders collected CSS styles loaded from components in the catalog. > **How does CSS loading work?** > > The CSS styles for components are loaded when the component is imported anywhere in your application. The > > `style.load()` > > method iterates over all imported components and checks if the components have any styles defined. All rendered HTML documents will have this component as a base similar to how all HTML pages in template engines like Jinja2 use the *base* template. > **How does a `Page` component differ from a regular component?** > > The only difference is that it renders as a valid HTML5 document starting with the > > `` > > declaration. You usually need only one > > `Page` > > component in the whole application. After you are done with setting up your `Page` component, you can use it along with all the other components in the catalog. ### HtmlPage Component This component has already been mentioned throughout the documentation and can be used to create your `Page` component. The `HtmlPage` component is just for convenience so that you can quickly start and not worry about how to load e.g. CSS styles or HTMX. Here is how you would use the `HtmlPage` component to create your own `Page` component: ```python from typing import override from ludic.attrs import NoAttrs from ludic.html import link, meta from ludic.catalog.pages import HtmlPage, Head, Body from ludic.catalog.layouts import Stack from ludic.components import Component from ludic.types import AnyChildren class Page(Component[AnyChildren, NoAttrs]): @override def render(self) -> HtmlPage: return HtmlPage( Head( # add custom head elements meta(charset="utf-8"), link(rel="icon", type="image/png", href="..."), # here is a list of the Head's (optional) attributes title="My Page", # add custom title favicon="favicon.ico", # add favicon path load_styles=True, # load registered styles htmx_config=..., # configure HTMX ), Body( # here you can create a base layout where all children of # this Page component will be placed, more about layouts # in the layouts section Stack(*self.children), # here is a list of the Body's (optional) attributes htmx_version="2.0.11", # loads HTMX script from CDN htmx_path="htmx.js", # loads HTMX script from a path htmx_enabled=True, # enable HTMX ), ) ``` Here are the default values: - `load_styles=True` - `htmx_config={"defaultSwapStyle": "outerHTML"}` - `htmx_enabled=True` - `htmx_version="latest"` Now that you prepared your `Page` component, you can use it in your code like here: ```python from ludic.web import LudicApp from ludic.catalog.buttons import Button from ludic.catalog.headers import H1 from ludic.catalog.typography import Paragraph from your_app.pages import Page app = LudicApp() @app.get("/") def index(request: Request) -> Page: return Page( H1("Hello, World!"), Button("Click Me", hx_get=request.url_for("clicked").path), ) @app.get("/clicked") def clicked(request: Request) -> Paragraph: return Paragraph("You clicked me!") ``` The `HtmlPage` component comes also with default `styles`. In fact, the following list of styles are auto-loaded whenever you import anything from the `ludic.catalog` module: - `ludic.catalog.pages` - `ludic.catalog.layouts` Source: https://getludic.dev/catalog/ --- # Layouts Layouts create a flexible structure for your user interface. The layouts in this module are based on the **Every Layout Book**. If you haven't read the book, go read it now: - [Every Layout Book](https://every-layout.dev/) These layouts allow us to create complex user interfaces with minimal CSS which are responsive and readable on all devices. The layouts can be combined together. All layouts are located in the `ludic.catalog.layouts` module. > **Viewing this page on mobile devices** > > If you are viewing this page on mobile devices, you won't probably see the layouts examples correctly rendered. You can always switch between desktop mode and mobile if you want to see the difference in rendering. ## Ideology In this module, layouts are designed as simple, reusable components that you can easily combine to create responsive, readable, and maintainable user interfaces. Instead of starting from scratch with basic HTML elements and manually writing CSS, you use these layouts as your **foundational building blocks**. This approach allows you to compose and arrange them in various ways to design your desired user interface, making your code more organized and easier to manage. **A New Way of Thinking About Design** When writing CSS, you might be tempted to apply e.g. specific spacing, colors, or font styles to an HTML element like a button. The idea of using the layout classes here is to define **context** which determines how an HTML element should be displayed. So for example, we might want to have a couple of buttons on one line, so we wrap them in a Cluster class which inserts a margin between all its children and puts them on one line. In another context, we want to widen a button so that it uses all available space and is displayed like a block element. In that case we use the Stack class. To illustrate this concept, here is a button wrapped in a Cluster: Here are the buttons wrapped in a Stack: Let's see the code: ```python from ludic.catalog.buttons import Button from ludic.catalog.layouts import Cluster, Stack Cluster(Button("In a Cluster"), Button("In a Cluster")) Stack(Button("In a Stack"), Button("In a Stack")) ``` ## Stack In the Stack layout, there's margin inserted between all its children elements, and each child occupies all the available horizontal space. So, essentially, each child stretches out horizontally as much as possible, with margins separating them. #### Usage ```python from ludic.catalog.layouts import Stack from ludic.html import div Stack( div("One"), div("Two"), div("Three"), ) ``` #### Use Cases - Separating paragraphs in large texts - Creating a list of posts on a blog site - Separating menu and body on a page ## Box The Box layout adds padding around its content from all directions. This means that there is an equal amount of space between the content and the edges of the box, including the left, right, top, and bottom sides. By default, the Box also includes a border and a background that is not transparent. #### Usage ```python from ludic.catalog.layouts import Box Box("Content") ``` #### Use Cases - Creating a page menu or sidebar - Making important text stand out on a page - Using it to highlight a list of actions (buttons) ## Center The Center layout ensures that its content stays centered on the page. It sets a maximum width for this content. If the content's width exceeds this maximum, instead of extending beyond the sides of the page, equal margins are created on both sides to keep the content centered. #### Usage ```python from ludic.catalog.layouts import Center, Stack from ludic.catalog.typography import Paragraph Center( Stack( Paragraph("Lorem ipsum"), Paragraph("Lorem ipsum"), ) ) ``` #### Use Cases - Main content of a web page - Ideal layout for blog sites ## Cluster The Cluster layout, when applied, adds margin between all of its inline children elements. It arranges all of its children elements on a single line until there is enough space on the page. It's important to note that the cluster layout is not intended to be used for block-level children elements like paragraphs. #### Usage ```python from ludic.catalog.buttons import Button, ButtonPrimary from ludic.catalog.layouts import Cluster Cluster( Button("Cancel"), ButtonPrimary("Save"), ) ``` #### Use Cases - Groups of elements that differ in length - Buttons appearing together at the end of a form - A list of tags or keywords ## Sidebar The Sidebar layout enables you to have two blocks on a page with equal height but different widths. Typically, the sidebar is narrower than the main content area. If there isn't enough space to display both the sidebar and the main content side by side, the layout adjusts into a stack-like format, where one block is stacked on top of the other. #### Usage ```python from ludic.catalog.layouts import Box, Sidebar, Stack, WithSidebar from ludic.catalog.typography import Paragraph WithSidebar( Sidebar( div("My Sidebar"), ), Stack( H1("Content"), Paragraph("Lorem ipsum"), ), ) ``` #### Use Cases - A page with menu and content - A list of actions next to a form ### Right Sidebar You can also have the sidebar on the right side instead of left. #### Usage ```python from ludic.catalog.layouts import Box, Sidebar, Stack, WithSidebar from ludic.catalog.typography import Paragraph WithSidebar( Stack( H1("Content"), Paragraph("Lorem ipsum"), ), Sidebar( div("My Sidebar"), ), ) ``` ## Switcher The Switcher layout ensures that all of its children elements have the same width until there is enough space available to display their content. However, if the layout is placed on a page where there isn't sufficient room, it collapses and switches to a stack-like format for display. #### Usage ```python from ludic.catalog.layouts import Switcher from ludic.html import div Switcher( div("One"), div("Two"), div("Three"), ) ``` #### Use Cases - Card components advertising products ## Cover The Cover layout consists of a header, content and footer. The header is placed above the content and the footer is placed below. The content is centered both horizontally and vertically. #### Usage ```python from ludic.catalog.layouts import Cover Cover( div("Header"), h1("Title"), div("Footer"), ) ``` #### Use Cases - Introductory page for a website ## Grid The Grid layout creates a grid of blocks with equal height and width. #### Usage ```python from ludic.catalog.layouts import Grid Grid( div("One"), div("Two"), div("Three"), div("Four"), div("Five"), ) ``` #### Use Cases - Teasers for permalinks or products ## Frame The Frame layout maintains aspect ratio even if it means the content needs to be cropped. #### Usage ```python from ludic.catalog.layouts import Frame from ludic.html import img Frame( img(src="/path/to/image", alt="my image"), ) ``` #### Use Cases - cropping media (videos and images) to a desired aspect ratio ## Complex Example You are free to combine layouts and components together. The following is an example of a complex layout consisting of multiple nested layouts mentioned in this tutorial. Slightly modified code of the layout is shown below. ```python Center( Stack( Box( Cluster( b("Inverse Boxed Cluster Menu"), Cluster( Button("Item 1"), ... ), classes=["justify-space-between"], ), classes=["invert"], ), WithSidebar( Stack( H2("Stack", anchor=False), Paragraph(...), H3("Switcher", anchor=False), Switcher( Box("Switcher Item 1"), ... ), H3("Cluster In a Box", anchor=False), Box( Cluster( ButtonPrimary("Cluster Button 1"), ..., ), ), H3("Grid Advertisement", anchor=False), Grid(Box(...), ...), ), Sidebar( Box( Stack( H3("Sidebar", anchor=False), Button("The Sidebar Item 1"), ... ), ), ), ), classes=["large"], ), style={"margin-block": "2rem"}, ) ``` Source: https://getludic.dev/catalog/layouts --- # Typography The module `ludic.catalog.typography` contains the following components: #### Link This text contains a [link](https://getludic.dev/catalog/). ```python from ludic.catalog.typography import Link Link("link", to="https://getludic.dev") # appends target="_blank" Link("link", to="/") # does not append target="_blank" ``` #### Paragraph Here is some text wrapped in a paragraph. ```python from ludic.catalog.typography import Paragraph Paragraph("Here is some text wrapped in a paragraph.") ``` #### Code This text contains code: `let mut x = 0;` ```python from ludic.catalog.typography import Code Code("let mut x = 0;") ``` #### Code Block The following block contains a Rust code with syntax highlighting generated by Pygments: ```rust fn main() { println!("Hello, world!"); } ``` ```python from ludic.catalog.typography import CodeBlock CodeBlock( """ fn main() { println!("Hello, world!"); } """, language="rust" ) ``` #### Pairs ```python from ludic.catalog.items import Pair, Key, Value Pairs( Key("First Name:"), Value("John"), Key("Last Name:"), Value("Doe"), ) ``` #### List ```Python from ludic.catalog.lists import List, Item List( Item("A"), Item("B"), Item("C"), ) ``` - A - B - C #### Numbered List ```Python from ludic.catalog.lists import NumberedList, Item NumberedList( Item("One"), Item("Two"), Item("Three"), ) ``` 1. One 2. Two 3. Three ## Headers The module `ludic.catalog.headers` contains components rendering as HTML headers (h1-h4). # H1 ## H2 ### H3 #### H4 ```python from ludic.catalog.headers import H1, H2, H3, H4 H1("H1") H2("H2") H3("H3") H4("H4") ``` The module also contains the `Anchor` component, which can be used to create an anchor link next to the header. #### H4 With Anchor ```python from ludic.catalog.headers import Anchor, H4 H4("H4 With Anchor", anchor=Anchor("#", target="h4-with-anchor")) ``` It is possible to generate the anchor automatically using the `anchor=True` attribute: ### H3 With Anchor ```python from ludic.catalog.headers import H3 H3("H3 With Anchor", anchor=True) ``` Source: https://getludic.dev/catalog/typography --- # Buttons The module `ludic.catalog.buttons` contains the following buttons: ```python from ludic.catalog.buttons import ( Button, ButtonPrimary, ButtonSecondary, ButtonSuccess, ButtonInfo, ButtonWarning, ButtonDanger, ButtonLink ) Button("Button") ButtonPrimary("ButtonPrimary") ButtonSecondary("ButtonSecondary") ButtonSuccess("ButtonSuccess") ButtonInfo("ButtonInfo") ButtonWarning("ButtonWarning") ButtonDanger("ButtonDanger") ButtonLink("ButtonLink", to="/") ``` The `ButtonLink` component can be styled like any other button using the `classes` attribute: ```python from ludic.catalog.buttons import ButtonLink ButtonLink("ButtonLink", to="/", classes=["warning"]) ``` You can disable a button using the `disabled` attribute: ```python from ludic.catalog.buttons import Button Button("Button", disabled=True) ``` ## Button Sizes You can also change the size of the button appending the `small` or `large` class: ```python from ludic.catalog.buttons import ButtonPrimary ButtonPrimary("Small", classes=["small"]) ButtonPrimary("Normal") ButtonPrimary("Large", classes=["large"]) ``` Source: https://getludic.dev/catalog/buttons --- # Messages The module `ludic.catalog.messages` contains the following components: > **Message** > > Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi. > **MessageSuccess** > > Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi. > **MessageInfo** > > Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi. > **MessageWarning** > > Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi. > **MessageDanger** > > Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi. ```python from ludic.catalog.messages import ( Message, MessageSuccess, MessageInfo, MessageWarning, MessageDanger, Title ) Message(Title("Message"), "...") MessageSuccess(Title("MessageSuccess"), "...") MessageInfo(Title("MessageInfo"), "...") MessageWarning(Title("MessageWarning"), "...") MessageDanger(Title("MessageDanger"), "...") ``` Note that you don't need to specify the `Title` component. Here is how the message renders without the title: > Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Source: https://getludic.dev/catalog/messages --- # Forms These components located in `ludic.catalog.forms` are in an experimental mode. There is the possibility to automatically create form fields from annotations, but it is far from production-ready. ## Input Field The `InputField` component is the most basic form field. It is a wrapper around the `input` HTML element which also generates a label if not disabled. Here is what it looks like: ```python from ludic.catalog.forms import InputField InputField( label="First Name", placeholder="Your First Name", name="sample-input-field", ) ``` You can also create the input field without the label by not passing the `label` attribute: ```python from ludic.catalog.forms import InputField InputField( name="sample-input-field", ) ``` ## Select Field The `SelectField` component is a wrapper around the `select` HTML element. It also generates a label if not disabled. Here is what it looks like: ```python from ludic.catalog.forms import SelectField, Option SelectField( Option("Option 1"), Option("Option 2", selected=True), Option("Option 3"), label="Select Option", name="sample-select-field", ) ``` ## Text Area The `TextAreaField` component is a wrapper around the `textarea` HTML element. It also generates a label if not disabled. Here is what it looks like: ```python from ludic.catalog.forms import TextAreaField TextAreaField( name="sample-text-area", label="Description", ) ``` Similarly as for the input field, you can create the text area without the label. ## Choices The `ChoiceField` component is a wrapper around the `` HTML element. It also generates a label if not disabled. Here is what it looks like: ```python from ludic.catalog.forms import ChoiceField ChoiceField( name="sample-choice-field", label="Are you a vegetarian?", choices=[("yes", "Yes"), ("no", "No")], selected="no", ), ``` ## Form The `Form` component is a wrapper around the `form` HTML element. Here is a sample form: ```python from ludic.catalog.buttons import ButtonSuccess from ludic.catalog.forms import Form, InputField, TextAreaField from ludic.catalog.layouts import Cluster Form( InputField( name="sample-input-field", label="First Name", placeholder="Your First Name", ), TextAreaField( name="sample-text-area", label="Description", ), Cluster(ButtonSuccess("Submit")), ) ``` We use the `Cluster` component to create a form with multiple input fields and buttons. this component is described in the [Layouts section](https://getludic.dev/catalog/layouts). You can also have the input field and the button aligned horizontally using this layout component: ```python from ludic.catalog.buttons import ButtonSuccess from ludic.catalog.forms import Form, InputField, Option, SelectField from ludic.catalog.layouts import Cluster Form( Cluster( InputField(placeholder="First Name"), SelectField( Option("Age", disabled=True, selected=True), Option("0-18"), Option("18+"), ), ButtonSuccess("Submit"), ) ) ``` ## Generating Form Fields In some cases, the attributes of a component or class-based endpoint can be used to create form fields automatically using the `create_fields` function. Here is an example: ```python from typing import Annotated from ludic.attrs import Attrs from ludic.catalog.forms import FieldMeta, create_fields class PersonAttrs(Attrs): first_name: Annotated[str, FieldMeta()] last_name: Annotated[str, FieldMeta()] person = PersonAttrs(first_name="John", last_name="Doe") fields = create_fields(person, spec=PersonAttrs) ``` The `create_fields` function generates form fields from annotations. It generates only fields that are annotated with the `FieldMeta` dataclass, which looks like this: ```python @dataclass class FieldMeta: label: str | Literal["auto"] | None = "auto" kind: Literal["input", "textarea", "checkbox"] = "input" type: Literal["text", "email", "password", "hidden"] = "text" attrs: InputAttrs | TextAreaAttrs | None = None parser: Callable[[Any], PrimitiveChildren] | None = None ``` The `parser` attribute validates and parses the field. Here is how you would use it: ```python from typing import Annotated from ludic.attrs import Attrs from ludic.web.parsers import ValidationError from ludic.catalog.forms import FieldMeta def parse_email(email: str) -> str: if len(email.split("@")) != 2: raise ValidationError("Invalid email") return email class CustomerAttrs(Attrs): id: str name: Annotated[ str, FieldMeta(label="Email", parser=parse_email), ] ``` Fields created with the `create_fields` function can be than extracted from submitted form data using the [Parser class](https://getludic.dev/docs/web-framework#parsers). Source: https://getludic.dev/catalog/forms --- # Tables These components located in `ludic.catalog.tables` are in an experimental mode. There is the possibility to automatically create tables even containing form fields and actions from annotations, but it is far from production-ready. ## Creating a Table The `Table` component accepts a `TableHead` as the first item and any number of `TableRow` items. | First Name | Last Name | Age | |---|---|---| | John | Doe | 42 | | Jane | Smith | 23 | ```python from ludic.catalog.tables import Table, TableHead, TableRow Table( TableHead("First Name", "Last Name","Age"), TableRow("John", "Doe", 42), TableRow("Jane", "Smith", 23), classes=["text-align-center"], ) ``` You can also specify different types of header and body. It might happen that you created your own component representing the table head and body: ```python from ludic.catalog.tables import Table from your_app.components import PersonHead, PersonRow Table[PersonHead, PersonRow]( PersonHead("Name", "Age"), PersonRow("John", 42), PersonRow("Jane", 23), ) ``` Note that the type specification in the square brackets is only for the type-checkers to pass. ## Generating Table Rows The `create_rows` function can be used to generate rows in the table based on given specification. Here is an example: ```python from typing import Annotated from ludic.attrs import Attrs from ludic.catalog.tables import ColumnMeta, Table, create_rows class PersonAttrs(Attrs): id: Annotated[int, ColumnMeta(label="ID")] name: Annotated[str, ColumnMeta(label="Full Name")] email: Annotated[str, ColumnMeta(label="Email")] people: list[PersonAttrs] = [ {"id": 1, "name": "John Doe", "email": "john@j.com"}, {"id": 2, "name": "Jane Smith", "email": "jane@s.com"}, ] rows = create_rows(people, spec=PersonAttrs) table = Table(*rows) ``` This would render the following table: | ID | Full Name | Email | |---|---|---| | 1 | John Doe | john@j.com | | 2 | Jane Smith | jane@s.com | ### Table With Form Fields There is also an experimental support for tables containing form fields.The way it works is that you wrap your table in a form and use the `create_rows` function to generate the rows. Here is an example: ```python from typing import Annotated from ludic.attrs import Attrs from ludic.catalog.tables import ColumnMeta, Table, create_rows class ContactAttrs(Attrs): id: Annotated[int, ColumnMeta(identifier=True)] name: Annotated[str, ColumnMeta(label="Full Name")] email: Annotated[str, ColumnMeta(label="Email")] active: Annotated[ bool, ColumnMeta( label="Active", kind=FieldMeta(kind="checkbox", label=None) ) ] contacts: list[ContactAttrs] = [ {"id": 1, "name": "John Doe", "email": "john@j.com", "active": True}, {"id": 2, "name": "Jane Smith", "email": "jane@s.com", "active": False}, ] rows = create_rows(contacts, spec=ContactAttrs) table = Table(*rows) ``` The role of the identifier column is to be able to parse the form data using the `ListParser` function as documented in the [Parsers section](https://getludic.dev/docs/web-framework#parsing-collections) of the documentation. Source: https://getludic.dev/catalog/tables --- # Loaders Loaders help load content asynchronously when the HTML page is rendered. The module currently contains only one loader requiring HTMX enabled. #### Lazy Loader ```python from ludic.catalog.loaders import LazyLoader LazyLoader(load_url="https://example.com/huge-image.png") ``` The default placeholder displayed before the content is loaded looks like this: However, you can use your own placeholder: ```python from ludic.catalog.loaders import LazyLoader, Loading LazyLoader( load_url="https://example.com/huge-image.png", placeholder=Loading(), # replace with your own placeholder ) ``` Source: https://getludic.dev/catalog/loaders --- # Components and Styling Here is a couple of examples how to write Ludic components, how to add custom HTML classes and register CSS properties. ## Link A simple component simulating a link. The component only accepts one string child and a `to` attribute. ```python from typing import override from ludic.attrs import Attrs from ludic.components import Component from ludic.html import a class LinkAttrs(Attrs): to: str class Link(Component[str, LinkAttrs]): classes = ["link"] @override def render(self) -> a: return a( *self.children, href=self.attrs["to"], style={"color": self.theme.colors.warning}, ) ``` ## Navigation A simple component which renders a navigation bar with a logo and a couple of links aligned to the right. This is what it looks like: And here is the code for this example: ```python from typing import override from ludic.attrs import NoAttrs from ludic.catalog.buttons import ButtonLink from ludic.catalog.layouts import Box, Cluster from ludic.components import Component from ludic.types import NoChildren class Navigation(Component[NoChildren, NoAttrs]): classes = ["sample-navigation"] @override def render(self) -> Box: return Box( Cluster( ButtonLink("Logo"), Cluster( ButtonLink("Item 1", to="..."), ButtonLink("Item 2", to="..."), ButtonLink("Item 3", to="..."), ButtonLink("Item 4", to="...", classes=["success"]), ), classes=["justify-space-between"], ), classes=["invert"], ) ``` Note that you need to use this navigation in the context of the [HtmlPage](https://getludic.dev/catalog/#htmlpage-component) component, otherwise there won't be the necessary CSS loaded. Or you can define your own styles for the component. ## Search Bar A simple component rendering a search bar with custom styling. Here is what it looks like: And here is the code for this example: ```python from typing import override from ludic.attrs import GlobalAttrs from ludic.catalog.forms import InputField from ludic.html import style from ludic.components import Component from ludic.types import NoChildren class SearchBar(Component[NoChildren, GlobalAttrs]): classes = ["search-bar"] styles = style.use( lambda theme: { ".search-bar": { "input": { "background-color": theme.colors.light.lighten(1), "border": f"1px solid {theme.colors.light.darken(5)}", "color": theme.colors.dark, }, "input::placeholder": { "color": theme.colors.dark.lighten(7), }, "input:focus": { "border-color": theme.colors.dark.lighten(5), "outline": "none", }, }, } ) @override def render(self) -> InputField: return InputField( type="search", placeholder="Custom search bar", **self.attrs, ) ``` Source: https://getludic.dev/examples/ --- ## Layout Example You are free to combine layouts and components together as described in the [Layouts](https://getludic.dev/catalog/layouts) section. The following is an example of a more complex layout consisting of multiple nested components using CSS utilities to tweak final design. Slightly modified code of the layout is shown below. ```python from ludic.catalog.buttons import ( Button, ButtonDanger, ButtonInfo, ButtonPrimary, ButtonSuccess, ) from ludic.catalog.headers import H2, H3 from ludic.catalog.layouts import ( Box, Center, Cluster, Grid, Sidebar, Stack, Switcher, WithSidebar, ) from ludic.catalog.typography import Paragraph from ludic.html import b Center( Stack( Box( Cluster( b("Inverse Boxed Cluster Menu"), Cluster( Button("Item 1"), ... ), classes=["justify-space-between"], ), classes=["invert"], ), WithSidebar( Stack( H2("Stack", anchor=False), Paragraph(...), H3("Switcher", anchor=False), Switcher( Box("Switcher Item 1"), ... ), H3("Cluster In a Box", anchor=False), Box( Cluster( ButtonPrimary("Cluster Button 1"), ..., ), ), H3("Grid Advertisement", anchor=False), Grid(Box(...), ...), ), Sidebar( Box( Stack( H3("Sidebar", anchor=False), Button("The Sidebar Item 1"), ... ), ), ), ), classes=["large"], ), style={"margin-block": "2rem"}, ) ``` Source: https://getludic.dev/examples/complex-layout --- # Bulk Update This demo shows how to implement a common pattern where rows are selected and then bulk updated. For the purpose of this example, we create a table containing people. We also create a column where we can mark the individual person as active or inactive. - [Full Code at GitHub](https://github.com/getludic/ludic/blob/main/examples/bulk_update.py) - [Source at htmx.org](https://htmx.org/examples/bulk-update/) ## Implementation The first thing we need to do is create the table. For this task, we use a class-based endpoint called `PeopleTable` which will contain the list of people. This list of people is going to be the endpoint's attributes, so we create them first: ```python from typing import Annotated from ludic.attrs import Attrs from ludic.catalog.forms import FieldMeta from ludic.catalog.tables import ColumnMeta class PersonAttrs(Attrs, total=False): id: Annotated[str, ColumnMeta(identifier=True)] name: Annotated[str, ColumnMeta()] email: Annotated[str, ColumnMeta()] active: Annotated[ bool, ColumnMeta(kind=FieldMeta(kind="checkbox", label=None)), ] class PeopleAttrs(Attrs): people: list[PersonAttrs] ``` Each field in the `PersonAttrs` definition is marked by the`Annotated` class containing the `ColumnMeta` marker. This marker helps generating the table using the `create_rows` function as we'll see bellow. Now we know what kind of data we need to store and what columns to create. Here is the endpoint implementation rendering the attributes as a table as well as handling the `GET` and `POST` HTTP methods: ```python from typing import Self, override from ludic.catalog.layouts import Cluster from ludic.catalog.tables import Table, create_rows from ludic.catalog.forms import Form from ludic.web import Endpoint, LudicApp from ludic.web.exceptions import NotFoundError from ludic.web.parsers import ListParser from your_app.attrs import PeopleAttrs, PersonAttrs from your_app.components import Toast from your_app.database import db app = LudicApp() @app.endpoint("/people/") class PeopleTable(Endpoint[PeopleAttrs]): @classmethod async def post(cls, data: ListParser[PersonAttrs]) -> Toast: items = {row["id"]: row for row in data.validate()} activations = {True: 0, False: 0} for person in db.people.values(): active = items.get(person.id, {}).get("active", False) if person.active != active: person.active = active activations[active] += 1 return Toast( t"Activated {activations[True]}, " t"deactivated {activations[False]}" ) @classmethod async def get(cls) -> Self: return cls(people=[person.dict() for person in db.people.values()]) @override def render(self) -> Form: return Form( Table(*create_rows(self.attrs["people"], spec=PersonAttrs)), Cluster( ButtonPrimary("Bulk Update", type="submit"), Toast(), ), hx_post=self.url_for(PeopleTable).path, hx_target=Toast.target, hx_swap="outerHTML settle:3s", ) ``` We created a class-based endpoint with the following methods: - `post` – handles the POST request which contains form data. Since we used the `create_rows` method, it is possible to use a parser to automatically convert the form data in a dictionary. In fact, we are handling a list of people, so we use the `ListParser`. Next, we update our database and return the number of activated and deactivated people as a `Toast` component that we cover bellow. - `get` – handles the GET request which fetches data about people from the database, creates a list of dicts from that and returns the table containing these people. - `render` – handles rendering of the table. The table is wrapped in a form so that it is possible to issue a POST request updating the list of active or inactive people. The form is wrapping the table having the columns created according the the `PersonAttrs` specification. We also need a button to submit the form and a `Toast` component which displays a message about activated and deactivated people. The form is submitted via HTMX. Here is the implementation of the `Toast` component displaying the small message next to the `Bulk Update` button: ```python from typing import override from ludic.html import span, style class Toast(span): id: str = "toast" target: str = f"#{id}" styles = style.use( lambda theme: { Toast.target: { "background": theme.colors.success, "padding": f"{theme.sizes.xxxxs} {theme.sizes.xxxs}", "font-size": theme.fonts.size * 0.9, "border-radius": "3px", "opacity": "0", "transition": "opacity 3s ease-out", }, f"{Toast.target}.htmx-settling": { "opacity": "100", }, } ) @override def render(self) -> span: return span(*self.children, id=self.id) ``` Source: https://getludic.dev/examples/bulk-update --- # Click To Edit The click to edit pattern provides a way to offer inline editing of all or part of a record without a page refresh. In this example, we create a customer which we'll be able to edit. - [Full Code at GitHub](https://github.com/getludic/ludic/blob/main/examples/click_to_edit.py) - [Source at htmx.org](https://htmx.org/examples/click-to-edit/) ## Implementation Before we start implementing the endpoint rendering the HTML form, we also want to display the data of the customer. The task can be achieved by implementing the `Contact` endpoint which renders the data as a description list. The endpoint also requires the contact's attributes which we describe like this: ```python from typing import Annotated from ludic.attrs import Attrs from ludic.catalog.forms import FieldMeta class ContactAttrs(Attrs): id: NotRequired[str] first_name: Annotated[str, FieldMeta(label="First Name")] last_name: Annotated[str, FieldMeta(label="Last Name")] email: Annotated[ str, FieldMeta(label="Email", type="email", parser=email_validator) ] ``` You may have noticed we used the `Annotated` marker. The reason for that is that we want to automatically create a form based on this specification later. There is also the `email_validator` parser which can parse and validate email of the customer. The parser could be as simple as this: ```python from ludic.web.parsers import ValidationError def email_validator(email: str) -> str: if len(email.split("@")) != 2: raise ValidationError("Invalid email") return email ``` The `contact` endpoint handles rendering of the customer data as well as the `GET` and `PUT` HTTP methods: ```python from typing import Self, override from ludic.catalog.forms import Form, create_fields from ludic.catalog.layouts import Cluster, Stack from ludic.catalog.items import Pairs from ludic.web import Endpoint, LudicApp from ludic.web.exceptions import NotFoundError from ludic.web.parsers import Parser from your_app.attrs import ContactAttrs from your_app.database import db app = LudicApp() @app.endpoint("/contacts/{id}") class Contact(Endpoint[ContactAttrs]): @classmethod async def get(cls, id: str) -> Self: contact = db.contacts.get(id) if contact is None: raise NotFoundError("Contact not found") return cls(**contact.dict()) @classmethod async def put(cls, id: str, attrs: Parser[ContactAttrs]) -> Self: contact = db.contacts.get(id) if contact is None: raise NotFoundError("Contact not found") for key, value in attrs.validate().items(): setattr(contact, key, value) return cls(**contact.dict()) @override def render(self) -> Stack: return Stack( Pairs(items=self.attrs.items()), Cluster( Button( "Click To Edit", hx_get=self.url_for(ContactForm).path, ), ), hx_target="this", ) ``` We created a class-based endpoint with the following methods: - `get` – handles the GET request which fetches information about the contact from the database, and returns them as the `Contact` component to be rendered as HTML. - `put` – handles the PUT request which contains form data. Since we later use the `create_rows` method, it is possible to use a parser to automatically convert the form data into a dictionary. First, we check that we have the contact in our database, than we validate the data submitted by the user and update the contact in our database, and finally, we return the updated contact as the `Contact` component. - `render` – handles rendering of the contact data and a button to issue the HTMX swap operation replacing the content with an editable form. The last remaining piece is the `ContactForm` component: ```python @app.endpoint("/contacts/{id}/form/") class ContactForm(Endpoint[ContactAttrs]): @classmethod async def get(cls, id: str) -> Self: contact = db.contacts.get(id) if contact is None: raise NotFoundError("Contact not found") return cls(**contact.dict()) @override def render(self) -> Form: return Form( *create_fields(self.attrs, spec=ContactAttrs), Cluster( ButtonPrimary("Submit"), ButtonDanger("Cancel", hx_get=self.url_for(Contact).path), ), hx_put=self.url_for(Contact).path, hx_target="this", ) ``` This component only implements two methods: - `get` – handles the GET request which renders the form containing the contact data stored in the database. - `render` – handles rendering of the contact form, a button to submit the form, and also a button to cancel the edit operation. We use the HTMX swap operation to replace the form with the `Contact` component on submit or cancel. Source: https://getludic.dev/examples/click-to-edit --- # Click To Load This example shows how to implement click-to-load the next page in a table of data. We create a table containing a list of contacts which we lazy load whenever user clicks on a button. - [Full Code at GitHub](https://github.com/getludic/ludic/blob/main/examples/click_to_load.py) - [Source at htmx.org](https://htmx.org/examples/click-to-load/) ## Implementation First, we define the contact's attributes and also attributes of an endpoint-based component we'll use later to hold the contacts and the current page: ```python from ludic.attrs import Attrs class ContactAttrs(Attrs): id: str name: str email: str class ContactsSliceAttrs(Attrs): page: int contacts: list[ContactAttrs] ``` Now we need to create two components. First one to display the table layout and its header columns. The second one to load the contacts data in the form of the table's rows. The reason for separating these components is to avoid duplicated code. ```python from typing import Self, override from ludic.catalog.tables import Table, TableHead, TableRow from ludic.components import Blank, Component from ludic.web import Endpoint, LudicApp from your_app.attrs import ContactAttrs, ContactsSliceAttrs from your_app.database import db from your_app.components import LoadMoreButton app = LudicApp() @app.get("/") async def table_of_contacts() -> ContactsTable: return ContactsTable(await ContactsSlice.get(QueryParams(page=1))), @app.endpoint("/contacts/") class ContactsSlice(Endpoint[ContactsSliceAttrs]): @classmethod async def get(cls, params: QueryParams) -> Self: page = int(params.get("page", 1)) return cls(page=page, contacts=db.load_contacts_page(page)) @override def render(self) -> Blank[TableRow]: next_page = self.attrs["page"] + 1 return Blank( *( TableRow(contact["id"], contact["name"], contact["email"]) for contact in self.attrs["contacts"] ), TableRow( td( LoadMoreButton( url=( f"{self.url_for(ContactsSlice).path}" f"?page={next_page}" ), ), colspan=3, ), id=LoadMoreButton.target, ), ) class ContactsTable(Component[ContactsSlice, Attrs]): @override def render(self) -> Table[TableHead, ContactsSlice]: return Table( TableHead("ID", "Name", "Email"), *self.children, classes=["text-align-center"], ) ``` First endpoint is function-based and is rendering the initial table of contacts. We use the `ContactsSlice.get()` method to load the first page. It would probably be better to separate this loading to some handler function. The `ContactsSlice` endpoint-based component is loading the table rows and implements two methods: - `get` – handles the GET request which loads contacts from the database. The handler returns an instance of itself. - `render` – handles rendering of the table rows and the `Load More` button. In order for everything to work properly, we render only the table's rows while wrapping them in the `Blank` component. This component does not render any HTML element, it's just a wrapper when we want to render a list of elements. Last, the `ContactsTable` class is a regular component that renders the table's columns. The last remaining piece is the `LoadMoreButton` component which triggers the `GET` request calling the `ContactsSlice` method to load more contact data: ```python from typing import override from ludic.attrs import Attrs from ludic.catalog.buttons import ButtonPrimary from ludic.components import ComponentStrict class LoadMoreAttrs(Attrs): url: str class LoadMoreButton(ComponentStrict[LoadMoreAttrs]): target: str = "replace-me" @override def render(self) -> ButtonPrimary: return ButtonPrimary( "Load More Agents...", hx_get=self.attrs["url"], hx_target=f"#{self.target}", ) ``` We use the HTMX swap operation to replace the button itself with a new slice of contacts rendered by the `ContactsSlice` endpoint. That is, the next page of rows as well as the button itself running the HTMX operation. Since the `ContactsSlice` always bumps the button link's page, we get the next page of contacts on every click. Source: https://getludic.dev/examples/click-to-load --- # Delete Row This example shows how to implement a delete button that removes a table row upon completion. For this example, we use have a sample database of people which we display in a table. Each row in the table can be deleted by clicking a button and a confirmation prompt. - [Full Code at GitHub](https://github.com/getludic/ludic/blob/main/examples/delete_row.py) - [Source at htmx.org](https://htmx.org/examples/delete-row/) ## Implementation Since we want to display people as rows in a table, we can create a dedicated class-based endpoint which can render itself like a component. Before we do that, we also need to declare what kind of data this endpoint handles: ```python from ludic.attrs import Attrs class PersonAttrs(Attrs): id: str name: str email: str active: bool class PeopleAttrs(Attrs): people: list[PersonAttrs] ``` Now we can use these attributes in our class-based endpoint: ```python from typing import override from ludic.catalog.tables import Table, TableRow from ludic.catalog.buttons import ButtonDanger from ludic.components import Component from ludic.web import Endpoint, LudicApp from ludic.web.exceptions import NotFoundError from starlette.responses import Response from your_app.attrs import PersonAttrs from your_app.database import db app = LudicApp() @app.endpoint("/people/{id}") class PersonRow(Endpoint[PersonAttrs]): @classmethod def delete(cls, id: str) -> Response: try: db.people.pop(id) except KeyError: raise NotFoundError("Person not found") return Response() @override def render(self) -> TableRow: return TableRow( self.attrs["name"], self.attrs["email"], "Active" if self.attrs["active"] else "Inactive", ButtonDanger( "Delete", hx_delete=self.url_for(PersonRow).path, classes=["small"] ), ) ``` We created a class-based endpoint with the following methods: - `delete` – handles the DELETE request which removes a person from the database. It returns an empty `200` response, which tells htmx to replace the row with nothing. Returning `None` would send `204 No Content`, and htmx does not swap anything on a 204. - `render` – handles rendering of the table. Apart from the textual columns, we also render an action button to delete a row which is hooked to the `PersonRow.delete()` method. The last remaining part is the table with people itself. We can create another class-based endpoint for this task: ```python from typing import override from ludic.catalog.tables import Table, TableRow from ludic.catalog.buttons import ButtonDanger from ludic.components import Component from ludic.web import Endpoint, LudicApp from your_app.attrs import PeopleAttrs from your_app.database import db # ... the PersonRow class is omitted here @app.endpoint("/people/") class PeopleTable(Endpoint[PeopleAttrs]): styles = { "tr.htmx-swapping td": { "opacity": "0", "transition": "opacity 1s ease-out", } } @classmethod def get(cls) -> Self: return cls(people=[person.dict() for person in db.people.values()]) @override def render(self) -> Table[TableHead, PersonRow]: return Table( TableHead("Name", "Email", "Active", ""), *(PersonRow(**person) for person in self.attrs["people"]), body_attrs=HtmxAttrs( hx_confirm="Are you sure?", hx_target="closest tr", hx_swap="outerHTML swap:1s", ), classes=["text-align-center"], ) ``` We created a class-based endpoint with the following methods: - `get` – handles the GET request which returns an instance of the `PeopleTable` filled with a list of people fetched from database. - `render` – handles rendering of the table of people. We use a special `body_attrs` attribute to configure HTMX operations on the `tbody` element. Source: https://getludic.dev/examples/delete-row --- # Edit Row This example shows how to implement editable rows. In this example, we create a table with a row for each person in the database. Each row contains an edit button which allows inline editing of user's data. - [Full Code at GitHub](https://github.com/getludic/ludic/blob/main/examples/edit_row.py) - [Source at htmx.org](https://htmx.org/examples/edit-row/) ## Implementation In this example, we'll be creating three class-based endpoints: 1. One for displaying the person's information in a row with the edit button; 2. Another for displaying the form for editing the person's data and an action button to confirm the changes; 3. Last one for displaying the whole table of people. First, we create the attributes which define what kind of data we want to display: ```python from typing import Annotated, NotRequired from ludic.attrs import Attrs from ludic.catalog.tables import ColumnMeta class PersonAttrs(Attrs): id: NotRequired[str] name: Annotated[str, ColumnMeta()] email: Annotated[str, ColumnMeta()] class PeopleAttrs(Attrs): people: list[PersonAttrs] ``` Now we create the `PersonRow` endpoint for displaying the person's information in a row: ```python from typing import Self, override from ludic.base import JavaScript from ludic.catalog.buttons import ButtonPrimary from ludic.catalog.tables import TableRow from ludic.web import Endpoint, LudicApp from ludic.web.parsers import Parser from your_app.attrs import PersonAttrs from your_app.database import db app = LudicApp() @app.endpoint("/people/{id}") class PersonRow(Endpoint[PersonAttrs]): on_click_script: JavaScript = JavaScript( """ let editing = document.querySelector('.editing') if (editing) { alert('You are already editing a row') } else { htmx.trigger(this, 'edit') } """ ) @classmethod async def put(cls, id: str, data: Parser[PersonAttrs]) -> Self: person = db.people.get(id) if person is None: raise NotFoundError("Person not found") for attr, value in data.validate().items(): setattr(person, attr, value) return cls(**person.dict()) @classmethod async def get(cls, id: str) -> Self: person = db.people.get(id) if person is None: raise NotFoundError("Person not found") return cls(**person.dict()) @override def render(self) -> TableRow: return TableRow( self.attrs["name"], self.attrs["email"], ButtonPrimary( "Edit", hx_get=self.url_for(PersonForm).path, hx_trigger="edit", on_click=self.on_click_script, classes=["small"], ), ) ``` We created a class-based endpoint, here is the explanation of its individual parts: - `on_click_script` – this script is executed when the edit button is clicked. We don't want to allow the user to edit multiple rows at once so we check if the user is already editing a row. - `put` – handles the PUT request which updates a person in the database. We return the updated person data as a row in the response. - `get` – handles the GET request which returns an instance of the `PeopleRow` of the requested person. - `render` – handles rendering of the row. Apart from the textual columns, we also render an action button to edit a row. Now, we want to create an endpoint which renders the form we want to display when a row is being edited: ```python from typing import Self, override from ludic.catalog.buttons import ButtonSecondary, ButtonSuccess from ludic.catalog.forms import InputField from ludic.catalog.tables import TableRow from ludic.web import Endpoint from your_app.attrs import PersonAttrs from your_app.database import db @app.endpoint("/people/{id}/form/") class PersonForm(Endpoint[PersonAttrs]): @classmethod async def get(cls, id: str) -> Self: person = db.people.get(id) if person is None: raise NotFoundError("Person not found") return cls(**person.dict()) @override def render(self) -> TableRow: return TableRow( InputField(name="name", value=self.attrs["name"]), InputField(name="email", value=self.attrs["email"]), Cluster( ButtonSecondary( "Cancel", hx_get=self.url_for(PersonRow).path, classes=["small"], ), ButtonSuccess( "Save", hx_put=self.url_for(PersonRow).path, hx_include="closest tr", classes=["small"], ), classes=["cluster-small"], ), classes=["editing"], ) ``` We created a class-based endpoint with the following methods: - `get` – handles the GET request which renders the requested person's row. - `render` – handles rendering of the person's edit row. Apart from the name and email columns, we are also rendering two action buttons, one canceling the action and one saving the changes. The last class-based endpoint is for displaying the table of people: ```python from typing import Self, override from ludic.catalog.tables import Table, TableHead from ludic.web import Endpoint from your_app.attrs import PeopleAttrs from your_app.database import db # ... PersonRow and PersonForm classes omitted along with the imports @app.endpoint("/people/") class PeopleTable(Endpoint[PeopleAttrs]): @classmethod async def get(cls) -> Self: return cls(people=[person.dict() for person in db.people.values()]) @override def render(self) -> Table[TableHead, PersonRow]: return Table[TableHead, PersonRow]( TableHead("Name", "Email", "Action"), *(PersonRow(**person) for person in self.attrs["people"]), body_attrs=HtmxAttrs( hx_target="closest tr" ), classes=["text-align-center"], ) ``` We created a class-based endpoint with the following methods: - `get` – handles the GET request which returns an instance of the `PeopleTable` filled with a list of people fetched from database. - `render` – handles rendering of the table of people. We use a special `body_attrs` attribute to configure HTMX operations on the `tbody` element. Source: https://getludic.dev/examples/edit-row --- # Infinite Scroll The infinite scroll pattern provides a way to load content dynamicallyon user scrolling action. This example is almost identical the the [Click To Load](https://getludic.dev/examples/click-to-load). - [Full Code at GitHub](https://github.com/getludic/ludic/blob/main/examples/infinite_scroll.py) - [Source at htmx.org](https://htmx.org/examples/infinite-scroll/) ## Implementation Check the [Click To Load](https://getludic.dev/examples/click-to-load) example. The only difference is the `render()` implementation with the introduction of the `hx_trigger` and `hx_swap` attributes. In the Click To Load example, we used the `LoadMoreButton` to trigger the load action. Here is the updated `render()` method: ```python @app.endpoint("/contacts/") class ContactsSlice(Endpoint[ContactsSliceAttrs]): ... @override def render(self) -> Blank[TableRow]: *init, last = ( (contact["id"], contact["name"], contact["email"]) for contact in self.attrs["contacts"] ) return Blank( *(TableRow(*rows) for rows in init), TableRow( *last, hx_get=( f"{self.url_for(ContactsSlice).path}" f"?page={self.attrs['page'] + 1}" ), hx_trigger="revealed", hx_swap="afterend", ), ) ``` Source: https://getludic.dev/examples/infinite-scroll --- # Lazy Loading This example shows how to lazily load an element on a page. This lazy loading can be used for loading large images. - [Full Code at GitHub](https://github.com/getludic/ludic/blob/main/examples/lazy_loading.py) - [Source at htmx.org](https://htmx.org/examples/lazy-load/) ## Implementation The lazy loading functionality is super simple to implement in Ludic. You can create just two function-based endpoints and use the `LazyLoader` component from the catalog: ```python from ludic.catalog.headers import H3 from ludic.catalog.layouts import Box, Frame from ludic.catalog.loaders import LazyLoader from ludic.web import LudicApp, Request app = LudicApp() @app.get("/") async def index(request: Request) -> LazyLoader: return LazyLoader(load_url=request.url_for(load_content).path) @app.get("/load/") async def load_content() -> Box: return Box( Frame( H3("Content Loaded"), ) ) ``` Source: https://getludic.dev/examples/lazy-loading --- # Cascading Selects (FastAPI) The cascading selects example uses **FastAPI** to implement two selects. First one is a simple select of a car's manufacturer. Second select's values are based on the option chosen by the first one. - [Full Code at GitHub](https://github.com/getludic/ludic/blob/main/examples/fastapi_example.py) - [Source at htmx.org](https://htmx.org/examples/value-select/) ## Implementation In this example, we are using FastAPI instead of Starlette. So we need to install ludic with the `fastapi` extra: ``` pip install ludic[fastapi] ``` Next step is to import and set up all the necessary classes: ```python from fastapi import FastAPI from ludic.contrib.fastapi import LudicRoute app = FastAPI() app.router.route_class = LudicRoute ``` Now let us set up a database. In this case, we are using a fake database of data classes. In real example, you might want to use e.g. SQLAlchemy ORM session. Anyway, here is what it might look like: ```python def get_session(request: Request) -> Database: return request.scope["db"] # this is a fake database ``` Next step is to create our select boxes. The first one will be selecting manufacturers, while the second car's models: ```python from typing import override from ludic.catalog.forms import Option, SelectField, SelectFieldAttrs from ludic.catalog.layouts import Stack from ludic.components import Component class CarSelect(Component[str, SelectFieldAttrs]): """Ludic element representing car select.""" @override def render(self) -> SelectField: return SelectField( *[ Option(child, value=child.lower()) for child in self.children ], label=self.attrs.pop("label", "Car Manufacturer"), name="manufacturer", **self.attrs, ) class CarModelsSelect(Component[str, SelectFieldAttrs]): """Ludic element representing car models select.""" @override def render(self) -> SelectField: return SelectField( *[ Option(child, value=child.lower()) for child in self.children ], label=self.attrs.pop("label", "Car Model"), id="models", **self.attrs, ) ``` Finally, we can implement the FastAPI view which renders the initial page containing two select boxes: ```python from fastapi import Depends from ludic.web import Request # FastAPI is configured to use our custom # Request object from my_app import Database, get_db from my_app.components import CarSelect, CarModelsSelect @app.get("/") def index(request: Request, db: Database = Depends(get_db)) -> Stack: return Stack( CarSelect( *db.find_all_cars_names(), hx_get=request.url_for(models).path, hx_target="#models", ), CarModelsSelect(*db.find_first_car().models), ) ``` We also need to implement the view that returns the car models options: ```python from ludic.web.exceptions import NotFoundError # ... already imported stuff skipped @app.get("/models/") def models( manufacturer: str | None = None, db: Database = Depends(get_db) ) -> CarModelsSelect: if car := db.find_car_by_name(manufacturer): return CarModelsSelect(*car.models, label=None) else: raise NotFoundError("Car could not be found") ``` Source: https://getludic.dev/examples/cascading-selects