# WebComPy > WebComPy is a Python frontend framework running entirely in the browser via PyScript/Emscripten with SSR and static site generation (SSG) in standard CPython from a single codebase. **Core concepts** - **Dual-environment execution**: The same Python `webcompy` core code renders live DOM nodes in the browser (PyScript/Pyodide) and HTML strings on the server (CPython or server-side Emscripten/Pyodide ASGI), separating browser PyScript detection (`ENVIRONMENT == "pyscript"`) from Emscripten runtime mechanics (`IS_EMSCRIPTEN`, i.e., `platform.system() == "Emscripten"`) and switching ports via dependency injection (`RenderContext`). - **Reactivity by default**: `Signal`, `Computed`, `ReactiveList`, and `ReactiveDict` track dependencies automatically and update bound DOM text, attributes, lists (`repeat`), and conditional branches (`switch`) without manual DOM orchestration. - **Light DOM custom elements**: Components are Python functions decorated with `@define_component()` returning virtual element trees with props, slots, lifecycle hooks (`on_before_rendering`, `on_mounted`, `on_before_destroy`), and component-scoped CSS. - **SSR hydration transfer**: State created inside component setup with `use_state`, `use_computed`, `use_reactive_list`, `use_reactive_dict`, and `use_async_result` (and `HttpClient` / `load_text` results) transfers cleanly from SSR/SSG HTML into the browser without flash or double-fetching. - **ASGI coexistence**: WebComPy dev/prod servers are standard Starlette ASGI applications that can mount sub-apps (`WebComPyServerConfig.mounts`) or be embedded inside host FastAPI/Starlette applications, alongside typed JSON-RPC (`webcompy.rpc`). - **Current installation note**: Until the latest releases are published on PyPI, `webcompy`, `webcompy-server`, `webcompy-cli`, and `webcompy-testing` are installed via GitHub `#subdirectory=packages/` URLs (see Installation), while PyScript resolves `webcompy` from PyPI/wheels. **Important notes** - Always call `@define_component()` with parentheses; omitting arguments derives the custom-element tag from the function name (`HomePage` -> ``), and passing `"custom-tag"` overrides it explicitly. - Create reactive state via `use_state` / `use_reactive_list` / `use_reactive_dict` inside component setup functions when SSR-to-browser value transfer is needed. - No JavaScript build step or Node.js bundler is required for WebComPy applications. - Keep server/build configuration (`WebComPyBuildConfig`, `WebComPyServerConfig`, `StaticRoute`) in `webcompy_config.py`; keep browser-visible runtime config (`WebComPyAppConfig`) in your app module so server-only code never enters the browser wheel. - Prefer typed RPC contracts (`Procedure`, `StreamingProcedure`, `Subscription`) bound to `app.rpc` (`ProcedureRegistry`) and called via `RpcHttpClient` / `RpcWsClient` over ad-hoc untyped RPC endpoints. **Minimal working example** ```python from webcompy.app import WebComPyApp from webcompy.components import ComponentContext, define_component from webcompy.elements import DOMEvent, html from webcompy.signal import use_computed, use_state @define_component() def CounterApp(context: ComponentContext[None]): count = use_state(lambda: 0) doubled = use_computed(lambda: count.value * 2) def increment(_ev: DOMEvent) -> None: count.value += 1 return html.DIV( {}, html.H1({}, "Counter"), html.P({}, "Count: ", count, " (doubled: ", doubled, ")"), html.BUTTON({"@click": increment}, "+1"), ) app = WebComPyApp(root_component=CounterApp) ``` Serve locally with `uv run python -m webcompy start --dev`, materialize deployable artifacts once with `uv run python -m webcompy prebuild` (and run `start --prebuilt`), or export static HTML/wheels with `uv run python -m webcompy generate` (browser-only standalone usage calls `app.run()`). **Essential API cheat sheet** | Area | Module | Core Public Symbols | Purpose | |---|---|---|---| | App & Components | `webcompy.app`, `webcompy.components` | `WebComPyApp`, `WebComPyAppConfig`, `PluginScript`, `PrePaintStyle`, `pre_paint_vars`, `use_pre_paint_style`, `define_component`, `ComponentContext`, `on_before_rendering`, `on_mounted`, `on_before_destroy` | App bootstrap, config, pre-paint scripts/styles, Light DOM components, lifecycle hooks | | Reactive State | `webcompy.signal` | `Signal`, `Computed`, `ReactiveList`, `ReactiveDict`, `use_state`, `use_computed`, `use_reactive_list`, `use_reactive_dict`, `use_readonly_signal`, `effect` | Reactive state primitives, setup-scoped transfer state, tracked side effects | | Elements & Flow | `webcompy.elements` | `html`, `DOMEvent`, `DomNodeRef`, `repeat`, `switch`, `Suspense`, `ErrorBoundary`, `ClientOnly`, `Teleport`, `Transition` | Typed HTML builders, keyed list reconciliation, async/error/portal/animation boundaries | | Templates & Assets | `webcompy.template`, `webcompy.resources` | `render_template`, `load_markdown_document`, `css_text`, `load_text`, `load_bytes` | HTML template interpolation, Markdown loading, package resource access | | Routing & DI | `webcompy.router`, `webcompy.di` | `Router`, `RouterLink`, `RouterView`, `RouterContext`, `use_router`, `lazy`, `InjectKey`, `provide`, `inject` | History/hash SPA routing, lazy routes, scoped dependency injection | | Async, HTTP & Forms | `webcompy.components`, `webcompy.ajax`, `webcompy.forms` | `use_async_result`, `use_async`, `HttpClient`, `Response`, `from_json`, `Field`, `Form`, `use_field`, `use_form`, `required`, `email` | Async setup data, typed HTTP client, reactive fields and validation | | Realtime & RPC | `webcompy.realtime`, `webcompy.rpc` | `use_event_source`, `use_websocket`, `Procedure`, `StreamingProcedure`, `Subscription`, `RpcHttpClient`, `RpcWsClient`, `ProcedureRegistry`, `batch`, `notify` | Shared SSE/WebSocket composables and contract-first typed JSON-RPC | | UI & i18n | `webcompy.ui`, `webcompy.ui.code_block`, `webcompy.i18n` | `CodeBlock`, `Input`, `Select`, `Modal`, `Drawer`, `Dropdown`, `Tabs`, `Alert`, `Card`, `Spinner`, `use_i18n`, `I18nManager` | First-party accessible UI primitives and SSR-consistent internationalization | | Server, CLI & Testing | `webcompy_server`, `webcompy_cli`, `webcompy_cli.config`, `webcompy_testing` | `configure_server_context`, `generate_html`, `create_asgi_app`, `create_prebuilt_asgi_app`, `prebuild_app`, `generate_static_site`, `run_server`, `PrebuildManifest`, `WebComPyBuildConfig`, `WebComPyServerConfig`, `StaticRoute`, `PWAConfig`, `TestRenderer`, `create_test_asgi_app`, `render_app_html` | ASGI embedding, dev/prod/prebuilt server, SSG export, headless component & ASGI testing | **Context bundles and Markdown endpoints** - Index only (overview, essential API cheat sheet, and `.md` page links — smallest file, tens of KB): https://webcompy.net/llms.txt - Compact single-file bundle (smaller alternative to `llms-full.txt` with Getting Started, Basic Usage, and Server & Tooling inlined; larger than the index, hundreds of KB): https://webcompy.net/llms-small.txt - Complete single-file bundle (all documentation pages with runnable demo sources inlined; ~1 MB+): https://webcompy.net/llms-full.txt - Per-page raw Markdown: append `.md` to any documentation page URL (for example, https://webcompy.net/documents/basic/components.md). --- Source: https://webcompy.net/documents/getting-started/what-is-webcompy.md (Category: Getting Started) # What is WebComPy WebComPy is a Python frontend framework. You write your UI in Python — components, routing, and state — and the same codebase runs in two places: in the browser via PyScript, and on the server via standard Python for pre-rendering. ## The dual-environment model Every WebComPy app lives in two runtimes: - **Browser (PyScript/Emscripten)**: reactive components render into the DOM, handle events, and update the page. This is where your app is interactive. - **Server (standard Python)**: the same components render to HTML for server-side rendering (SSR) and static site generation (SSG), so first loads are fast and crawlable. ```text Python components |-- browser --> interactive DOM (PyScript) |-- server --> pre-rendered HTML (SSR / SSG) ``` The framework detects the runtime with `platform.system() == "Emscripten"` and wires up the matching port implementations (DOM, fetch, scheduler) through dependency injection. Application code stays the same on both sides. ## Core promises - **Components**: plain functions decorated with `@define_component()` render as Light DOM custom elements. Props, slots, and scoped CSS included. - **Reactivity**: `Signal`, `Computed`, and reactive collections refresh the DOM automatically when state changes. - **Routing**: client-side routing with history and hash modes, path parameters, and navigation hooks. - **CLI and pre-rendering**: scaffold projects, run a dev server with live reload, and ship SSR or fully static output. - **Typed data flow**: schema-driven API clients, JSON-RPC with streaming and WebSocket transports, and server-to-browser hydration transfer. ## Relationship to FastAPI and Starlette WebComPy is not a replacement for your backend framework — it complements it: - The **dev server and SSR endpoints are ASGI apps**. You can embed a WebComPy serving app inside a host ASGI application (for example, next to FastAPI routes) and share the same process. - **Data fetching during SSR** goes through the same ASGI transport, so server-rendered pages can call your own API routes without leaving the process. - For typed client-server communication, WebComPy offers its own **JSON-RPC layer** (HTTP, streaming, and WebSocket), which sits alongside — not instead of — plain REST endpoints you already serve. - Already running a server-rendered Jinja2 + FastAPI app? Follow the step-by-step strangler strategy in [Migrating from Jinja2 + FastAPI](/documents/migration/from-jinja2-fastapi). ## Next steps If WebComPy sounds like a fit, read [Why WebComPy](/documents/getting-started/why-webcompy) for an honest discussion of trade-offs, then follow the [Installation](/documents/getting-started/installation) guide to set up a project. --- Source: https://webcompy.net/documents/getting-started/why-webcompy.md (Category: Getting Started) # Why WebComPy Choosing a framework is a trade-off. This page states both sides plainly so you can decide with open eyes. ## Why WebComPy - **One language for the whole frontend**: components, routing, state, and data fetching are all Python. No context-switching between a Python backend and a JavaScript frontend. - **Reactivity without ceremony**: `Signal` and `Computed` values refresh the DOM automatically. You describe what the UI should show, not how to update it. - **Pre-rendering built in**: server-side rendering and static site generation come from the same component code — fast first loads without a separate pipeline. - **Typed client-server flow**: schema-driven API clients and JSON-RPC (HTTP, streaming, WebSocket) keep the contract between browser and server explicit. - **Familiar ecosystem**: the browser runtime is Python via PyScript, so libraries you already know — including numpy and friends — work where the runtime supports them. ## Why not WebComPy At the time of writing, the following drawbacks are real. Weigh them before committing: - **PyScript payload and cold start**: the browser must load the Python runtime before your app starts. Initial loads are heavier and slower than a hand-tuned JavaScript bundle, especially on slow networks. - **Young ecosystem**: fewer third-party components, integrations, and answered questions than mainstream JavaScript frameworks. You will occasionally build what elsewhere you would install. - **Performance ceiling**: Python in the browser cannot match compiled JavaScript for hot loops and large-scale DOM churn. Apps with heavy per-frame computation may need to push work to the server or to JavaScript. - **Browser-API coverage gaps**: newer or niche web APIs may not yet have a framework wrapper, leaving you to write interop code yourself. - **Smaller hiring and community pool**: finding developers and reviewers with WebComPy experience is harder than with established frameworks. None of these are permanent — runtime size, coverage, and community all move over time — but they describe the framework as it exists today. ## The short version Choose WebComPy when a Python-only stack, declarative reactivity, and built-in pre-rendering outweigh raw bundle size and ecosystem maturity for your project. If minimal cold-start latency or a vast plugin ecosystem is the top priority, a mainstream JavaScript framework is currently the safer pick. ## Next steps Continue to the [Installation](/documents/getting-started/installation) guide to set up a project, or skim [What is WebComPy](/documents/getting-started/what-is-webcompy) for the architectural picture. --- Source: https://webcompy.net/documents/getting-started/installation.md (Category: Getting Started) # Installation > **Note**: Until the latest release is published to PyPI, the packages are resolved from the GitHub repository via the `git+` URLs below. Once the packages are on PyPI, the install commands can be simplified (e.g. `uv add webcompy-cli` / `poetry add webcompy-cli` / `pip install webcompy[cli]`). PyScript loads `webcompy` from PyPI and does not yet support installing from a GitHub repository, so the version loaded in PyScript is the last published one. ## Prerequisites - Python 3.12 or later. - `uv` (recommended) or `Poetry` as the project package manager. ## Install with uv (Recommended) Create a new project and set up dependencies using `uv`. ```bash mkdir webcompy-project && cd webcompy-project uv init uv add "webcompy @ git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy" uv add "webcompy-server @ git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy-server" uv add "webcompy-cli @ git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy-cli" uv run python -m webcompy init ``` ## Browser dependencies Browser dependencies are third-party packages loaded by PyScript in the browser (for example `numpy` or `matplotlib` for demos). Declare them as an optional dependency group named `browser` in `pyproject.toml` so the CLI can resolve and lock them for the PyScript runtime: ```toml [project.optional-dependencies] browser = ["numpy", "matplotlib"] ``` This step is optional — skip it if your app needs no third-party packages in the browser. ## Project configuration `webcompy init` generates `webcompy_config.py`. The base shape mirrors the scaffold template: ```python # webcompy_config.py import app.app as app_module from webcompy_cli.config import WebComPyBuildConfig, WebComPyServerConfig config = WebComPyBuildConfig( app_module, dependencies=None, # explicit browser package list (None = resolve from pyproject) dependencies_from=None, # pyproject group to read browser deps from (e.g. "browser") server=WebComPyServerConfig(port=8080), # dev server and SSR serving options ) ``` - `app_module`: your application package — the `WebComPyApp` instance the CLI builds and serves. - `dependencies`: an explicit list of browser packages. Leave `None` to resolve from `pyproject.toml` instead. - `dependencies_from`: the `pyproject.toml` group those packages are read from. Set `"browser"` to use the `[project.optional-dependencies] browser` group above. - `server`: serving-only options such as the dev server port. It never affects the browser bundle. When you use the `browser` group, pair it with lockfile sync so `webcompy-lock.json` tracks that group: ```python from webcompy_cli.config import LockfileSyncConfig config = WebComPyBuildConfig( app_module, dependencies=None, dependencies_from="browser", lockfile_sync_config=LockfileSyncConfig(sync_group="browser"), server=WebComPyServerConfig(port=8080), ) ``` ## Lock file & dev server Generate the lock file and start the dev server: ```bash uv run python -m webcompy lock uv run python -m webcompy start --dev ``` Note: `webcompy lock --install` uses `uv pip` or `pip`, not `poetry install`. Use `webcompy lock --sync` to compare versions with `pyproject.toml`. ## Install with Poetry If you prefer Poetry, use the following setup: ```bash poetry new webcompy-project && cd webcompy-project poetry add "git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy" poetry add "git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy-server" poetry add "git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy-cli" poetry run python -m webcompy init ``` Add browser dependencies to `[project.optional-dependencies]` in `pyproject.toml` (same as the uv setup above), then configure `webcompy_config.py` as shown above, and run: ```bash poetry run python -m webcompy lock poetry run python -m webcompy start --dev ``` Note: `webcompy lock --install` uses `uv pip` or `pip`, not `poetry install`. Use `webcompy lock --sync` to compare versions with `pyproject.toml`. --- Source: https://webcompy.net/documents/getting-started/quickstart.md (Category: Getting Started) # Quickstart ## Create a project After installing WebComPy, scaffold a new project inside an existing Python project: ```bash uv run python -m webcompy init ``` The command generates the application entry point, a router, and a set of example components under your project. It also creates `webcompy_config.py` so the CLI knows how to build and serve your app. ## Start the dev server Start the development server with live reload: ```bash uv run python -m webcompy start --dev ``` The server prints the URL of your app (default: `http://localhost:8080`). Open it in a browser to see the template page running in PyScript. ## Your first component Components are plain functions decorated with the `@define_component()` factory. Open `app/components/home.py` and replace its body with your own view: ```python from webcompy.components import ComponentContext, define_component from webcompy.elements import html from webcompy.router import RouterContext @define_component() def HomePage(context: ComponentContext[RouterContext]): context.set_title("My First App") return html.H1( {}, "Hello WebComPy!", ) ``` The custom element name is derived from the function name (`HomePage` → ``); pass it explicitly with `@define_component(custom_element_name="home-page")` when you want a different tag. Every component renders as a custom element. Components return an element tree built with the `html` helpers. Reactive state comes from `Signal`, `use_state`, and `use_computed`; the framework refreshes the DOM automatically when the state changes. ## Next steps Head to the [Installation](/documents/getting-started/installation) guide for the full setup reference, or explore the demos in the navigation bar to see components, routing, and reactive state in action. --- Source: https://webcompy.net/documents/getting-started/project-structure.md (Category: Getting Started) # Project Structure Running `webcompy init` inside an existing Python project scaffolds an application package with this layout: ```text webcompy-project/ ├── app/ │ ├── __init__.py │ ├── app.py # the WebComPyApp instance │ ├── router.py # route table │ └── components/ # your components (home.py, ...) ├── webcompy_config.py # build + server configuration ├── pyproject.toml # project metadata and browser dependencies ├── webcompy-lock.json # locked browser dependency versions ├── static/ # static files served as-is └── dist/ # generated output (SSG) ``` ## The app package `app/app.py` holds the `WebComPyApp` instance — the central object that owns routes, head metadata, styles, and scripts. `app/router.py` maps URL paths to lazily-loaded components, and `app/components/` holds the components themselves. Each component file defines one or more `@define_component()` functions that render as custom elements. ## Configuration: build vs server `webcompy_config.py` separates two concerns in one file: ```python config = WebComPyBuildConfig( app_module, # your app package (imported as a module) dependencies=None, # explicit browser deps (or resolve from pyproject) dependencies_from=None, # e.g. "browser": read browser deps from pyproject server=WebComPyServerConfig(port=8080), # dev server / SSR serving options ) ``` - The **`WebComPyBuildConfig`** fields (`dependencies`, `dependencies_from`, lockfile sync) control how browser dependencies are resolved and locked for the PyScript runtime. - The **`server`** field (`WebComPyServerConfig`) controls serving only — port, and related runtime options. It never affects the browser bundle. Each field is explained in place where it appears; the [Installation](/documents/getting-started/installation) guide walks through a complete example including the browser-dependency variant. ## Static files and resources The `static/` directory holds files served verbatim — stylesheets, images, and other assets your pages reference. App-package resource files (text resources transferred to the browser) go through the resource port with an allow-list, so only declared resources are exposed. ## The lockfile `webcompy-lock.json` pins the exact browser dependency versions resolved from `pyproject.toml`. It is generated by `webcompy lock` and keeps every machine — and the PyScript runtime — on identical versions. The lock workflow (`lock`, `lock --sync`, `lock --export`, `lock --install`) is covered in the [Installation](/documents/getting-started/installation) guide. `dist/` is generated output from `webcompy generate` (static site generation). It is a build artifact, not source — regenerate rather than edit it. ## Next steps With the layout in mind, head to the [Quickstart](/documents/getting-started/quickstart) to render your first component, inspect the full field reference in [Project Configuration](/documents/server/project-configuration) and [CLI Reference](/documents/server/cli-reference), or browse the demos in the navigation bar. --- Source: https://webcompy.net/documents/basic/components.md (Category: Basic Usage) # Components Components are the building blocks of a WebComPy user interface. In WebComPy, every component is a Python function decorated with `@define_component()` that returns an element tree and renders in the browser as a **Light DOM custom element** (no Shadow DOM). Use components whenever you want a reusable piece of UI with its own props, slots, local reactive state, lifecycle hooks, or scoped CSS. ## At a glance A component receives a `ComponentContext` and returns elements built with `html` helpers or `render_template`: ```python from webcompy.components import ComponentContext, define_component from webcompy.elements import html @define_component() def GreetingCard(context: ComponentContext[dict[str, str]]): name = context.props.get("name", "World") return html.DIV( {"class": "card"}, html.H2({}, f"Hello, {name}"), context.slots("default", fallback=lambda: html.P({}, "Welcome to WebComPy.")), ) # Render it inside another component: GreetingCard( {"name": "Alice"}, slots={"default": lambda: html.P({}, "Glad you are here.")}, ) ``` Calling `GreetingCard(...)` emits `...` in both server-rendered HTML and the browser DOM. ## Defining components and tag names `define_component` is a decorator factory — always call it with parentheses: - **Derived tag name (default)**: calling `@define_component()` converts the PascalCase function name to kebab-case (`GreetingCard` → ``, `TodoListPage` → ``). - **Explicit tag name**: pass a tag positionally or by keyword when you want a different custom element tag: ```python @define_component(custom_element_name="user-badge") def Badge(context: ComponentContext[None]): return html.SPAN({}, "Member") ``` Custom element names in the HTML specification must contain at least one hyphen and cannot use reserved names (such as `font-face`). Single-word function names like `App` derive `app` with no hyphen and raise `WebComPyComponentException` at definition time — rename the function to a multi-word PascalCase name (such as `TodoApp`) or pass `custom_element_name=` explicitly. ### Returning multiple roots Because the custom element tag acts as a real DOM wrapper, a component can return a single `Element` or a sequence (`list` or `tuple`) of elements without an extra wrapping `
`: ```python @define_component() def ArticleHeader(context: ComponentContext[None]): return [ html.H1({}, "Release Notes"), html.P({}, "Latest framework updates"), ] ``` ## Props and slots Components accept `(props, *, slots=None)`: - **Props (`context.props`)**: any Python value (commonly a `dict`, `TypedDict`, dataclass, or `RouterContext`) annotated via `ComponentContext[PropsType]`. Use `ComponentContext[None]` when a component takes no props. - **Slots (`context.slots`)**: pass `slots={"slot_name": lambda: ...}` from the parent and invoke `context.slots(name, fallback=...)` inside the component. The primary body slot is named `"default"`. ```python @define_component() def PanelCard(context: ComponentContext[dict[str, str]]): return html.SECTION( {"class": "panel"}, html.HEADER({}, context.slots("header", fallback=lambda: html.STRONG({}, context.props["title"]))), html.DIV({}, context.slots("default")), html.FOOTER({}, context.slots("footer", fallback=lambda: "")), ) ``` > **Note**: Each slot entry is a zero-argument generator (`lambda: ...`) rather than an already-built node, so the component controls when and where the slot renders. Returning `None` from `fallback=lambda: None` omits optional regions cleanly. ## Lifecycle hooks Register hooks inside component setup using decorators imported from `webcompy.components` (or the equivalent methods on `context`): | Hook | Timing | Typical use | |---|---|---| | `@on_before_rendering` | Before initial render | Reset per-visit state, prepare data | | `@on_after_rendering` | After render completes | Post-render work | | `@on_mounted` | After wrapper connects to browser `document` | DOM measurement, focus, third-party widget init | | `@on_unmounted` | After wrapper disconnects from `document` | Disconnect browser observers | | `@on_before_destroy` | Before component disposal | Cancel timers, close manual subscriptions | Both sync functions and `async def` coroutines are accepted: ```python from webcompy.components import ( ComponentContext, define_component, on_before_destroy, on_before_rendering, on_mounted, ) from webcompy.elements import html @define_component() def StatusPanel(context: ComponentContext[None]): @on_before_rendering def prepare(): print("Preparing status panel") @on_mounted def connected(): print("Mounted into the browser document") @on_before_destroy def cleanup(): print("Disposing component resources") return html.DIV({}, "Status: ready") ``` For document metadata inside page components, call `context.set_title("Page Title")` and `context.set_meta(key, {...})` during setup. ## Scoped styles and host display Attach a static style dictionary to `.scoped_style` after defining the component. WebComPy scopes selectors to the component using its `webcompy-cid-*` attribute and outputs them in the `webcompy-scope` cascade layer: ```python @define_component(display="block") def InfoBanner(context: ComponentContext[None]): return html.P({"class": "message"}, "Heads up!") InfoBanner.scoped_style = { ":host": { "border": "1px solid var(--color-border)", "border-radius": "var(--radius-md)", "padding": "var(--space-3)", }, ".message": { "margin": "0", "font-weight": "600", }, } ``` ### The `display` keyword argument and `:host` By default, custom element wrappers use `display: contents` so they remain layout-transparent inside flex/grid parents and do not create an extra CSS box. Pass `display="block"` (or another `ComponentDisplay` value: `"inline"`, `"inline-block"`, `"flex"`, `"inline-flex"`, `"grid"`, `"inline-grid"`, `"flow-root"`, `"contents"`) on `@define_component(...)` — or target `:host` in `scoped_style` — when the component wrapper itself needs a box, background, border, or transition animation. ## Notes & caveats - Always call `@define_component()` with parentheses; bare `@define_component` without parentheses is not supported. - Component setup runs once per component mount, not on every reactive update. Read reactive state inside elements, templates, or `use_computed` rather than expecting setup to re-execute. - Do not register duplicate custom element tags in the same application — WebComPy rejects collisions at definition time. ## Next steps - See a minimal runnable component app in the [Hello World](/documents/examples/hello-world) example. - Learn how to write component views with HTML syntax in [HTML Templates](/documents/basic/template-html). - Explore [Styling & Themes](/documents/basic/styling-and-themes) for cascade layers, `css_text`, and theme tokens. - When you need `observed_attributes`, browser/test lifecycle nuances, or custom-element JavaScript interop, continue to [Custom Elements](/documents/advanced/custom-elements). - Full API: [App & Components API](/documents/api/app-and-components). --- Source: https://webcompy.net/documents/basic/template-html.md (Category: Basic Usage) # HTML Templates `render_template()` lets you write HTML markup instead of nested `html.DIV(...)` calls. It parses your template string at compile time using Python's `html.parser.HTMLParser` and returns a standard WebComPy `Element` tree with full reactive bindings preserved. Use HTML templates whenever a component view reads more cleanly as HTML, while keeping Python components and slots for composition. ## At a glance Pass an HTML template string (with a single root element) and a context dictionary to `render_template`: ```python from webcompy.components import ComponentContext, define_component from webcompy.signal import Signal from webcompy.template import render_template @define_component() def CounterBanner(context: ComponentContext[None]): count = Signal(0) def increment(_ev): count.value += 1 return render_template( """ """, {"count": count, "increment": increment}, ) ``` ## Interpolation and reactivity Use `{{ expr }}` in text content or HTML attribute values: - **Direct Signal reference**: `{{ count }}` passes the `Signal` directly into a reactive text node or attribute — updates are surgical with zero intermediate wrapper. - **Expression or dotted path through a Signal**: expressions like `{{ count * 2 }}`, `{{ "even" if count % 2 == 0 else "odd" }}`, or `{{ user.profile.name }}` when `profile` is a `Signal` automatically wrap in an implicit `Computed` so the DOM updates whenever any referenced Signal changes. - **Static context values**: plain strings, numbers, `Element`, and `Component` objects are inserted directly without extra reactive overhead. A `None` variable renders nothing in text positions and `""` in attribute interpolation. - **Boolean attributes**: valueless attributes such as `

Hello {{ name | default("stranger") }}

""", {"name": name, "input_ref": input_ref, "focus_input": focus_input}, ) ``` Only `:ref` and `:bind` are valid `:`-prefixed attributes on standard HTML elements. To compute regular HTML attributes dynamically, use `{{ ... }}` (e.g., `class="{{ item_class }}"`). ## Component tags in templates Any hyphenated tag not in standard HTML (such as ``) resolves via the application's component registry by converting kebab-case to PascalCase (`` → `UserCard`). Plain attributes become string props, `:`-prefixed props pass context variables (preserving Signals), and element children become the component's `"default"` slot: ```html

Shown inside the default slot.

``` Note that `:`-prefixed prop names convert kebab-case to snake_case in `context.props` (`:item-count` → `context.props["item_count"]`). ## Notes & caveats - **Single root element**: `render_template()` requires exactly one top-level root element (`
...
`). Return multiple roots at the component boundary with a Python `list` if needed. - **Rejected HTML tags**: `