/ludic:ludic-componentsfrom ludic
Guides writing typed, React-like HTML components in Python with Ludic (PEP 750 t-strings, Python 3.14+). Covers subclassing Component, declaring Attrs TypedDicts, composing HTML elements, catalog widgets, htmx attributes, themes, and the Safe content boundary.
Ships in ludic. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Ludic is a Python framework for building HTML pages with a typed, React-like component model that pairs with htmx. v1.x targets Python 3.14+ and uses PEP 750 t-strings (template strings) for templating.
This skill helps you write idiomatic Ludic components: well-composed, type-safe under mypy (with the Ludic mypy plugin), safe by default, and legible. For wiring components into a web app (endpoints, request handling, URL generation, framework integrations), use the companion ludic-web skill.
Look at the project's dependencies (pyproject.toml, the lock file) before writing code:
t"...". Everything in this skill is written for 1.x.p(f"Hello {b('World')}!"). Ludic 0.5 renders the elements inside these f-strings correctly. The rest of the API is the same, apart from features added in 1.x.Three layers, top to bottom:
ludic.html (div, a, html, head, body, table, form, ...). Each element has a typed signature describing its allowed children and attributes (e.g. br() accepts no children; html(...) requires head as the first child, body as the second).ludic.components — Component[TChildren, TAttrs] and the variadic ComponentStrict[*TChildrenArgs, TAttrs]. You subclass these and implement render(), which returns an element tree. Components are the unit of reuse and can carry CSS via class-level classes and styles declarations and read the current Theme via self.theme.ludic.catalog — opinionated widgets built on top of the core: layouts (PageLayout, Stack, Cluster, Sidebar), forms (Form, FormField), tables (Table, TableHead, TableRow), navigation, typography, buttons, messages, etc. Reach for these before composing layouts out of raw divs — they encode sensible defaults.The rendering pipeline runs once when you call .to_html(): it walks children, expands any t-string Template instances, escapes untrusted text, formats attributes (aliases like class_ → class, dict-style style={...}, list-style classes=[...]), and emits a single HTML string.
In v1.x, code that mixes HTML elements with interpolated text uses t-strings (PEP 750), not f-strings:
from ludic.html import b, div
# correct — v1.x
div(t"Hello {b('World')}!")
# wrong — f-strings eagerly stringify b(...), losing escaping and child-tracking
div(f"Hello {b('World')}!")
The t"..." literal produces a Template object that Ludic's element constructor detects and expands. If you see f"... {some_element} ..." mixing HTML elements with text, change it to t"...".
Everything is HTML-escaped by default. To opt out — for content you've already verified is safe HTML — wrap it in Safe:
from ludic.html import div
from ludic.types import Safe
div("Hello <b>World</b>").to_html()
# → '<div>Hello <b>World</b></div>' (escaped — safe default)
div(Safe("Hello <b>World</b>")).to_html()
# → '<div>Hello <b>World</b></div>' (raw — you take responsibility)
Only use Safe for content you control or have sanitized. Never wrap user input in Safe — that's the XSS hole this whole system exists to prevent. There's also JavaScript(Safe) for inline JS bodies.
Ludic also speaks the __html__ protocol used by MarkupSafe, Jinja2 and Django, in both directions:
__html__ (markupsafe.Markup, Django's mark_safe(...) result) is trusted like Safe and written as it is. This applies to children only; attribute values are escaped unless they are Safe.Safe string implements __html__, so {{ component }} in a Jinja2 or Django template renders the markup instead of escaping it.Elements also implement _repr_html_, so a notebook cell that ends with an element displays the rendered HTML.
Two component classes:
Component[TChildren, TAttrs] — accepts a variable number of children all of one type, plus a single TAttrs TypedDict for attributes.ComponentStrict[*TChildrenArgs, TAttrs] — uses a TypeVarTuple to enforce an exact positional sequence of child types (e.g. "exactly one TableHead followed by zero-or-more TableRow").Use ComponentStrict when the shape of children matters structurally; use Component when children are a homogeneous list.
from typing import override
from ludic import Attrs, Component
from ludic.html import a
class LinkAttrs(Attrs):
to: str
class Link(Component[str, LinkAttrs]):
classes = ["link"] # CSS classes added to the rendered root
styles = {"a.link": {"color": "blue"}} # collected by the style system
@override
def render(self) -> a:
return a(
*self.children,
href=self.attrs["to"],
style={"color": self.theme.colors.primary},
)
To render several elements without a wrapping element, return Blank(...) from render(). It renders only its children and escapes text like any other element.
A few rules the Ludic mypy plugin enforces — make sure your app's pyproject.toml (or mypy.ini) has plugins = ["ludic.mypy_plugin"], otherwise mypy does not check the attributes passed to components (see Check your work):
Component[...] / ComponentStrict[...] synthesize __init__, so call sites get checked against TChildren and TAttrs.Attrs (and the per-element TypedDicts in ludic.attrs) describe allowed attributes. Unknown attributes are a type error.class_ → class, for_ → for, hx_get → hx-get, etc. The style= attribute accepts a dict; classes= accepts a list.htmx attributes are exposed as hx_* keyword arguments on every element with GlobalAttrs:
from ludic.html import button
button(
"Load more",
hx_get="/items?page=2",
hx_target="#items",
hx_swap="beforeend",
)
When you serve the rendered HTML from an endpoint, htmx swaps it into the page. The endpoint side is covered in the ludic-web skill — including how to generate the URLs you pass to hx_get / hx_post safely.
Before composing a layout out of divs, check ludic.catalog:
catalog.pages — HtmlPage, Head, Body: a whole HTML document with the collected CSS and, optionally, the htmx script (Body(..., htmx_version="2.0.4")). Head(dark_theme=...) and ColorSchemeToggle add a dark mode (see Theming and styles).catalog.layouts — Stack, Box, Center, Cluster, Sidebar, WithSidebar, Switcher, Cover, Grid, Frame (adapted from Every Layout).catalog.forms — Form, FormField, InputField, TextAreaField, SelectField with Option, ChoiceField, and create_fields with FieldMeta, which builds form fields from an Attrs TypedDict.catalog.tables — Table, TableHead, TableRow.catalog.navigation — Navigation with NavItem for a menu, NavBar for a sticky bar at the top of the page, and TableOfContents(*page_elements), which links to the H2 headings among the elements.catalog.tabs — Tabs with Tab(content, label="..."), which switch without JavaScript.catalog.cards — Card, a framed box for short content; put cards in a Grid for responsive columns, and pass to="/url" to make a card a link.catalog.typography — Paragraph, Link, Code, and CodeBlock, which takes language=, a label= such as a file name, and copy_button=True.catalog.buttons, catalog.messages, catalog.loaders, catalog.headers, catalog.items, catalog.lists, catalog.quotes, catalog.icons.These are also the best place to learn idiomatic Ludic — they exercise the full surface area of the framework.
Component subclasses can declare:
classes: list[str] — appended to the root element's class list at render time.styles: GlobalStyles — collected at startup so you can emit a single <style> block for the page.Read the active theme via self.theme (returns the default theme if none is in scope). Themes flow down the tree automatically, so children see the same theme as the parent rendering them.
For a dark mode, give Head a second theme. The page then follows the system setting, and ColorSchemeToggle lets the visitor switch and remembers the choice:
from ludic.catalog.pages import Body, ColorSchemeToggle, Head, HtmlPage
from ludic.catalog.typography import Paragraph
from ludic.styles.themes import DarkTheme, LightTheme
page = HtmlPage(
Head(title="My App", theme=LightTheme(), dark_theme=DarkTheme()),
Body(ColorSchemeToggle(), Paragraph("Hello!"), htmx_version="2.0.4"),
)
assert 'media="(prefers-color-scheme: dark)"' in page.to_html()
Both themes must have different names, because the styles are cached per theme name. Put colors in styles rather than in inline style={...} attributes, because inline styles do not switch with the theme.
To restyle catalog components, change the theme instead of writing CSS for them. Make your theme the default with set_default_theme when the app starts. Head(theme=...) alone changes only the collected CSS; the styles that components compute in render(), such as the highlighting in CodeBlock, come from the default theme.
from dataclasses import dataclass, field
from ludic.styles import themes
from ludic.styles.types import Color, ColorRange
@dataclass
class BrandTheme(themes.LightTheme):
name: str = "brand"
colors: themes.Colors = field(
default_factory=lambda: themes.Colors(
primary=ColorRange(["#1e3a8a", "#1d4ed8", "#dbeafe"]),
)
)
fonts: themes.Fonts = field(
default_factory=lambda: themes.Fonts(secondary="Georgia, serif")
)
layouts: themes.Layouts = field(
default_factory=lambda: themes.Layouts(
sidebar=themes.Sidebar(side_width="18rem")
)
)
code: themes.CodeBlock = field(
default_factory=lambda: themes.CodeBlock(
color=Color("#e2e8f0"),
background_color=Color("#0f172a"),
style="github-dark",
)
)
themes.set_default_theme(BrandTheme())
What the fields change:
colors: primary colors links and ButtonPrimary; secondary, success, info, warning and danger color the button and message variants; white is the page background, dark the text, light the background of default buttons and inline code. A ColorRange lists the shades from the darkest to the lightest, and darken() / lighten() step through them.fonts: primary for text, secondary for headings, monospace for code, size for the base font size.layouts: sidebar.side_width, switcher.threshold, grid.cell_size, cover.min_height and the other settings of the catalog layouts.code: the colors, line numbers and Pygments style of CodeBlock. Import the theme's class through the module, as themes.CodeBlock, because the catalog's CodeBlock has the same name.buttons: the color and background_color of the default Button and ButtonLink.measure, line_height, sizes, borders, rounding and headers, which sets the size of each heading and whether H1–H4 get an anchor.Give every theme its own name. The Themes page describes every setting.
from typing import override
from ludic import Attrs, Component
from ludic.catalog.layouts import Stack
from ludic.catalog.typography import Paragraph
from ludic.html import b, h2
class GreetingAttrs(Attrs):
name: str
class Greeting(Component[str, GreetingAttrs]):
classes = ["greeting"]
@override
def render(self) -> Stack:
return Stack(
h2(t"Hello, {b(self.attrs['name'])}!"),
Paragraph(*self.children),
)
# Usage
Greeting("Welcome to Ludic.", name="Ada").to_html()
What to notice:
Component[str, GreetingAttrs] says: children are strings, attrs match GreetingAttrs.h2(t"Hello, {b(...)}!") keeps b(...) as a real element — it isn't stringified.self.attrs['name'] flows into b(...) and is HTML-escaped on output (because it isn't wrapped in Safe).Stack from the catalog handles vertical spacing — no need to roll a div with margin classes.Run mypy with the Ludic plugin after writing or changing components, and fix what it reports before you finish:
# pyproject.toml
[tool.mypy]
plugins = ["ludic.mypy_plugin"]
mypy path/to/your/package
Use mypy 2.0 or newer. Older versions do not support t-strings and report each one as PEP 750 template strings are not yet supported. Upgrade mypy instead of rewriting the t-strings as f-strings.
mypy with the plugin reports:
ul or an element in a Component[str, ...];br;html needs head and then body.Other type checkers do not run mypy plugins, so none of them checks the attributes passed to components:
Expected `LinkAttrs`, found `Literal["/home"]` , even in valid code. Do not change valid code to silence these errors.Run mypy even when the editor shows no errors.
To see what a component renders, call .to_html() on it, e.g. in a test.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub getludic/ludic --plugin ludic2 skills in this plugin
Other plugins' skills for the same job