### Fasthx Jinja Setup and Decorator Usage Source: https://github.com/volfpeter/fasthx/blob/main/docs/examples/jinja-templating.md Demonstrates initializing Fasthx Jinja with FastAPI and Jinja2Templates, and applying the `@jinja.page()` and `@jinja.hx()` decorators to routes for rendering HTML responses. `@jinja.page()` renders HTML unconditionally, while `@jinja.hx()` renders only for HTMX requests. ```python from fastapi import FastAPI from fastapi.templating import Jinja2Templates from fasthx import Jinja from pydantic import BaseModel # Pydantic model of the data the example API is using. class User(BaseModel): first_name: str last_name: str # Create the app. app = FastAPI() # Create a FastAPI Jinja2Templates instance and use it to create a # FastHX Jinja instance that will serve as your decorator. jinja = Jinja(Jinja2Templates("templates")) @app.get("/") @jinja.page("index.html") def index() -> None: ... # Placeholder for route logic @app.get("/user-list") @jinja.hx("user-list.html") async def htmx_or_data() -> list[User]: return [ User(first_name="John", last_name="Lennon"), User(first_name="Paul", last_name="McCartney"), User(first_name="George", last_name="Harrison"), User(first_name="Ringo", last_name="Starr"), ] @app.get("/admin-list") @jinja.hx("user-list.html", no_data=True) def htmx_only() -> list[User]: return [User(first_name="Billy", last_name="Shears")] ``` -------------------------------- ### Install FastHX Source: https://github.com/volfpeter/fasthx/blob/main/docs/index.md Install the FastHX package using pip. ```console pip install fasthx ``` -------------------------------- ### Run FastAPI Application Source: https://github.com/volfpeter/fasthx/blob/main/docs/examples/htmy.md Provides instructions on how to run the FastAPI application. It suggests using either the 'fastapi dev' CLI command or 'uvicorn' for development with hot-reloading. ```shell # Using fastapi CLI: fastapi dev htmy_app.py # Or using uvicorn: uvicorn htmy_app:app --reload ``` -------------------------------- ### Install FastHX with Optional Dependencies Source: https://github.com/volfpeter/fasthx/blob/main/docs/index.md Install FastHX with optional integrations for htmy or jinja templating engines. ```console pip install fasthx[htmy] pip install fasthx[jinja] ``` -------------------------------- ### Initialize FastAPI and FastHX HTMY Source: https://github.com/volfpeter/fasthx/blob/main/docs/examples/htmy.md Sets up the FastAPI application instance and the fasthx.htmy.HTMY instance. It demonstrates registering a request processor to add user-agent information to the HTMX rendering context. ```python from fastapi import FastAPI from fasthx.htmy import HTMY # Create the app instance. app = FastAPI() # Create the FastHX HTMY instance that renders all route results. htmy = HTMY( # Register a request processor that adds a user-agent key to the htmy context. request_processors=[ lambda request: {"user-agent": request.headers.get("user-agent")}, ] ) ``` -------------------------------- ### Install FastHX with pip Source: https://github.com/volfpeter/fasthx/blob/main/README.md Installs the FastHX package using pip. Supports optional dependencies for integrations like htmy and jinja. ```console pip install fasthx pip install fasthx[htmy] pip install fasthx[jinja] ``` -------------------------------- ### Create Index Page Route with HTMX Source: https://github.com/volfpeter/fasthx/blob/main/docs/examples/htmy.md Defines the root endpoint ('/') for the FastAPI application. It uses the @htmy.page decorator to render the IndexPage component when the route is accessed. ```python @app.get("/") @htmy.page(lambda _: IndexPage()) def index() -> None: """The index page of the application.""" ... ``` -------------------------------- ### Create Users Route with HTMX Component Header Source: https://github.com/volfpeter/fasthx/blob/main/docs/examples/htmy.md Defines the '/users' endpoint which serves a list of users. It uses the @htmy.hx decorator with ComponentHeader to conditionally render different versions of the UserOverview component based on the 'X-Component' header, and demonstrates accessing query parameters. ```python from datetime import date import random from fasthx.htmy import ComponentHeader # Assuming User and UserOverview are defined elsewhere # class User: ... # class UserOverview: ... @app.get("/users") @htmy.hx( # Use a header-based component selector that can serve ordered or # unordered user lists, depending on what the client requests. ComponentHeader( "X-Component", { "ordered": lambda users: UserOverview(users, True), "unordered": UserOverview, }, default=UserOverview, ) ) def get_users(rerenders: int = 0) -> list[User]: """Returns the list of users in random order.""" result = [ User(name="John", birthday=date(1940, 10, 9)), User(name="Paul", birthday=date(1942, 6, 18)), User(name="George", birthday=date(1943, 2, 25)), User(name="Ringo", birthday=date(1940, 7, 7)), ] random.shuffle(result) return result ``` -------------------------------- ### Create User List Item Component Source: https://github.com/volfpeter/fasthx/blob/main/docs/examples/htmy.md A HTMY component that renders a single user's name and birthday within an `
  • ` HTML element. It utilizes basic HTML tags and TailwindCSS classes for styling. ```python @dataclass class UserListItem: """User list item component.""" user: User def htmy(self, context: Context) -> Component: return html.li( html.span(self.user.name, class_="font-semibold"), html.em(f" (born {self.user.birthday.isoformat()})"), class_="text-lg", ) ``` -------------------------------- ### Define Index Page Component with HTMX Source: https://github.com/volfpeter/fasthx/blob/main/docs/examples/htmy.md Defines the main HTML structure for the index page using fasthx components. It includes meta tags, TailwindCSS, and HTMX scripts, and a placeholder div for lazy-loaded content managed by HTMX. ```python from fasthx import html, Context, Component class IndexPage: def htmy(self, context: Context) -> Component: return ( html.DOCTYPE.html, html.html( html.head( # Some metadata html.title("FastHX + HTMY example"), html.meta.charset(), html.meta.viewport(), # TailwindCSS html.script(src="https://cdn.tailwindcss.com"), # HTMX html.script(src="https://unpkg.com/htmx.org@2.0.2"), ), html.body( # Page content: lazy-loaded user list. html.div(hx_get="/users", hx_trigger="load", hx_swap="outerHTML"), class_=( "h-screen w-screen flex flex-col items-center justify-center " " gap-4 bg-slate-800 text-white" ), ), ), ) ``` -------------------------------- ### Create User Overview Component with HTMX Source: https://github.com/volfpeter/fasthx/blob/main/docs/examples/htmy.md A HTMY component that displays a list of users and application state information like request URL, user agent, and rerender count. It uses HTMX attributes for self-reloading and demonstrates accessing request context and route parameters. ```python @dataclass class UserOverview: """ Component that shows a user list and some additional info about the application's state. The component reloads itself every second. """ users: list[User] ordered: bool = False def htmy(self, context: Context) -> Component: # Load the current request from the context. request = CurrentRequest.from_context(context) # Load route parameters (resolved dependencies) from the context. route_params = RouteParams.from_context(context) # Get the user-agent from the context which is added by a request processor. user_agent: str = context["user-agent"] # Get the rerenders query parameter from the route parameters. rerenders: int = route_params["rerenders"] # Create the user list item generator. user_list_items = (UserListItem(u) for u in self.users) # Create the ordered or unordered user list. user_list = ( html.ol(*user_list_items, class_="list-decimal list-inside") if self.ordered else html.ul(*user_list_items, class_="list-disc list-inside") ) # Randomly decide whether an ordered or unordered list should be rendered next. next_variant = random.choice(("ordered", "unordered")) # noqa: S311 return html.div( # -- Some content about the application state. html.p(html.span("Last request: ", class_="font-semibold"), str(request.url)), html.p(html.span("User agent: ", class_="font-semibold"), user_agent), html.p(html.span("Re-renders: ", class_="font-semibold"), str(rerenders)), html.hr(), # -- User list. user_list, # -- HTMX directives. hx_trigger="load delay:1000", hx_get=f"/users?rerenders={rerenders+1}", hx_swap="outerHTML", # Send the next component variant in an X-Component header. hx_headers=f'{{"X-Component": "{next_variant}"}}', # -- Styling class_="flex flex-col gap-4", ) ``` -------------------------------- ### Fasthx TemplateHeader for Dynamic Template Selection Source: https://github.com/volfpeter/fasthx/blob/main/docs/examples/jinja-templating.md Illustrates using `TemplateHeader` with the `@jinja.hx()` decorator to dynamically select which Jinja template to render based on a custom client header (e.g., 'X-Component'). It supports mapping header values to template paths and defining a default template. ```python from fastapi import FastAPI from fastapi.templating import Jinja2Templates from fasthx import Jinja, TemplateHeader from pydantic import BaseModel # Assume User model and get_user_from_db are defined elsewhere class User(BaseModel): first_name: str last_name: str def get_user_from_db(id: int) -> User: # Dummy implementation return User(first_name="John", last_name="Doe") app = FastAPI() jinja = Jinja(Jinja2Templates("templates")) @app.get("/profile/{id}") @jinja.hx( TemplateHeader( "X-Component", { "card": "profile/card.jinja", "form": "profile/form.jinja", }, default="profile/card.jinja", ) ) def get_user_by_id(id: int) -> User: return get_user_from_db(id) # Example of using prefix for template paths @app.get("/user-profile/{id}") @jinja.hx( TemplateHeader( "X-Component", { "card": "card.jinja", "form": "form.jinja", }, default="card.jinja", prefix="profile" ) ) def get_user_profile_by_id(id: int) -> User: return get_user_from_db(id) ``` -------------------------------- ### Define User Pydantic Model Source: https://github.com/volfpeter/fasthx/blob/main/docs/examples/htmy.md Defines a Pydantic model for user data, including name and birthday. This model serves as a data structure for user information within the application. ```python import random from dataclasses import dataclass from datetime import date from fastapi import FastAPI from htmy import Component, Context, html from pydantic import BaseModel from fasthx.htmy import HTMY, ComponentHeader, CurrentRequest, RouteParams class User(BaseModel): """User model.""" name: str birthday: date ``` -------------------------------- ### FastHX Custom Templating with FastAPI Source: https://github.com/volfpeter/fasthx/blob/main/docs/examples/custom-templating.md This example demonstrates how to use `hx()` and `page()` decorators with custom render functions in FastAPI. It shows integrating custom HTML rendering logic, accessing route dependencies within renderers, and handling both HTMX and standard page requests. ```python from typing import Annotated, Any from fastapi import Depends, FastAPI, Request from fasthx import hx, page # Create the app. app = FastAPI() # Create a dependecy to see that its return value is available in the render function. def get_random_number() -> int: return 4 # Chosen by fair dice roll. DependsRandomNumber = Annotated[int, Depends(get_random_number)] # Create the render methods: they must always have these three arguments. # If you're using static type checkers, the type hint of `result` must match # the return type annotation of the route on which this render method is used. def render_index(result: list[dict[str, str]], *, context: dict[str, Any], request: Request) -> str: return "

    Hello FastHX

    " def render_user_list(result: list[dict[str, str]], *, context: dict[str, Any], request: Request) -> str: # The value of the `DependsRandomNumber` dependency is accessible with the same name as in the route. random_number = context["random_number"] lucky_number = f"

    {random_number}

    " users = "".join(("")) return f"{lucky_number}\n{users}" @app.get("/") @page(render_index) def index() -> None: ... @app.get("/htmx-or-data") @hx(render_user_list) def htmx_or_data(random_number: DependsRandomNumber) -> list[dict[str, str]]: return [{"name": "Joe"}] @app.get("/htmx-only") @hx(render_user_list, no_data=True) async def htmx_only(random_number: DependsRandomNumber) -> list[dict[str, str]]: return [{"name": "Joe"}] ``` -------------------------------- ### APIDOC: fasthx.hx Decorator Configuration Source: https://github.com/volfpeter/fasthx/blob/main/docs/api/core-decorators.md Documents the configuration options for the `fasthx.hx` decorator. This decorator is used to configure HX-specific settings for a page or component. Key options include `show_root_heading`. ```APIDOC ::: fasthx.hx options: show_root_heading: true Description: Configures HX-specific settings for a component or page. Parameters: options (dict): show_root_heading (bool, optional): Determines if the root heading should be displayed. Defaults to true. ``` -------------------------------- ### APIDOC: fasthx.page Decorator Configuration Source: https://github.com/volfpeter/fasthx/blob/main/docs/api/core-decorators.md Documents the configuration options for the `fasthx.page` decorator. This decorator is used to configure page-specific settings. A primary option available is `show_root_heading`. ```APIDOC ::: fasthx.page options: show_root_heading: true Description: Configures page-specific settings. Parameters: options (dict): show_root_heading (bool, optional): Determines if the root heading should be displayed. Defaults to true. ``` -------------------------------- ### fasthx.Jinja API Source: https://github.com/volfpeter/fasthx/blob/main/docs/api/jinja.md API documentation for the Jinja class in the fasthx library. This entry details its methods, parameters, and return values. ```APIDOC ::: fasthx.Jinja options: show_root_heading: true ``` -------------------------------- ### fasthx.JinjaContext API Source: https://github.com/volfpeter/fasthx/blob/main/docs/api/jinja.md API documentation for the JinjaContext class in the fasthx library. This entry details its methods, parameters, and return values. ```APIDOC ::: fasthx.JinjaContext options: show_root_heading: true ``` -------------------------------- ### FastAPI Jinja2 Templating with fasthx Source: https://github.com/volfpeter/fasthx/blob/main/README.md Demonstrates using fasthx.Jinja with FastAPI for routing HTML and HTMX requests. Shows the `page()` decorator for unconditional HTML rendering and the `hx()` decorator for conditional HTMX rendering, along with Pydantic models and route definitions. ```Python from fastapi import FastAPI from fastapi.templating import Jinja2Templates from fasthx import Jinja from pydantic import BaseModel # Pydantic model of the data the example API is using. class User(BaseModel): first_name: str last_name: str # Create the app. app = FastAPI() # Create a FastAPI Jinja2Templates instance and use it to create a # FastHX Jinja instance that will serve as your decorator. jinja = Jinja(Jinja2Templates("templates")) @app.get("/") @jinja.page("index.html") def index() -> None: ... @app.get("/user-list") @jinja.hx("user-list.html") async def htmx_or_data() -> list[User]: return [ User(first_name="John", last_name="Lennon"), User(first_name="Paul", last_name="McCartney"), User(first_name="George", last_name="Harrison"), User(first_name="Ringo", last_name="Starr"), ] @app.get("/admin-list") @jinja.hx("user-list.html", no_data=True) def htmx_only() -> list[User]: return [User(first_name="Billy", last_name="Shears")] ``` -------------------------------- ### fasthx.JinjaContextFactory API Source: https://github.com/volfpeter/fasthx/blob/main/docs/api/jinja.md API documentation for the JinjaContextFactory class in the fasthx library, including its callable members like __call__. ```APIDOC ::: fasthx.JinjaContextFactory members: - __call__ options: show_root_heading: true ``` -------------------------------- ### Fasthx Component Selectors Configuration Source: https://github.com/volfpeter/fasthx/blob/main/docs/api/component_selectors.md Details configuration options for the fasthx.component_selectors module, specifically controlling the display of root headings in generated output. ```APIDOC fasthx.component_selectors: options: show_root_heading: boolean - Description: Controls whether a root heading is displayed for the component selectors. - Default: true - Example: show_root_heading: false ``` -------------------------------- ### fasthx.JinjaPath API Source: https://github.com/volfpeter/fasthx/blob/main/docs/api/jinja.md API documentation for the JinjaPath class in the fasthx library. This entry details its methods, parameters, and return values. ```APIDOC ::: fasthx.JinjaPath options: show_root_heading: true ``` -------------------------------- ### Use HTMX and HTMY with FastHX Source: https://github.com/volfpeter/fasthx/blob/main/README.md Demonstrates how to use FastHX with the htmy integration for server-side rendering. It shows how to decorate FastAPI routes with `htmy.hx()` and `htmy.page()` to render HTML components. ```python from datetime import date from fastapi import FastAPI from pydantic import BaseModel from fasthx.htmy import HTMY # Pydantic model for the application class User(BaseModel): name: str birthday: date # Create the FastAPI application. app = FastAPI() # Create the FastHX HTMY instance that renders all route results. htmy = HTMY() @app.get("/users") @htmy.hx(UserList) # Render the result using the UserList component. def get_users(rerenders: int = 0) -> list[User]: return [ User(name="John", birthday=date(1940, 10, 9)), User(name="Paul", birthday=date(1942, 6, 18)), User(name="George", birthday=date(1943, 2, 25)), User(name="Ringo", birthday=date(1940, 7, 7)), ] @app.get("/") @htmy.page(IndexPage) # Render the index page. def index() -> None: ... ``` -------------------------------- ### fasthx.TemplateHeader API Source: https://github.com/volfpeter/fasthx/blob/main/docs/api/jinja.md API documentation for the TemplateHeader class in the fasthx library. This entry details its methods, parameters, and return values. ```APIDOC ::: fasthx.TemplateHeader options: show_root_heading: true ``` -------------------------------- ### FastAPI Custom Templating with fasthx Decorators Source: https://github.com/volfpeter/fasthx/blob/main/README.md Illustrates using fasthx's `hx()` and `page()` decorators with custom render functions in FastAPI. Shows how to define render functions that accept `result`, `context`, and `request`, and how to access dependencies within the render context. ```Python from typing import Annotated, Any from fastapi import Depends, FastAPI, Request from fasthx import hx, page # Create the app. app = FastAPI() # Create a dependecy to see that its return value is available in the render function. def get_random_number() -> int: return 4 # Chosen by fair dice roll. DependsRandomNumber = Annotated[int, Depends(get_random_number)] # Create the render methods: they must always have these three arguments. # If you're using static type checkers, the type hint of `result` must match # the return type annotation of the route on which this render method is used. def render_index(result: list[dict[str, str]], *, context: dict[str, Any], request: Request) -> str: return "

    Hello FastHX

    " def render_user_list(result: list[dict[str, str]], *, context: dict[str, Any], request: Request) -> str: # The value of the `DependsRandomNumber` dependency is accessible with the same name as in the route. random_number = context["random_number"] lucky_number = f"

    {random_number}

    " users = "".join(("")) return f"{lucky_number}\n{users}" @app.get("/") @page(render_index) def index() -> None: ... @app.get("/htmx-or-data") @hx(render_user_list) def htmx_or_data(random_number: DependsRandomNumber) -> list[dict[str, str]]: return [{"name": "Joe"}] @app.get("/htmx-only") @hx(render_user_list, no_data=True) async def htmx_only(random_number: DependsRandomNumber) -> list[dict[str, str]]: return [{"name": "Joe"}] ``` -------------------------------- ### RequestComponentSelector API Changes for Exception Rendering Source: https://github.com/volfpeter/fasthx/blob/main/docs/migrations/1-to-2.md Version 2 of fasthx introduces exception rendering, requiring updates to custom `RequestComponentSelector` implementations. This includes renaming methods and adding an error parameter to handle exceptions gracefully. ```APIDOC RequestComponentSelector API Update: - Method Renaming: - Old: `get_component_id()` - New: `get_component()` - Description: Renames the method responsible for selecting request components. - Parameter Addition: - Old Signature (example): `get_component_id(...)` - New Signature (example): `get_component(error: Exception | None = None, ...)` - Description: Adds an optional `error` parameter to the component selection method. This parameter will receive the exception if an error occurred during request processing. - Protocol Behavior for Non-Error Rendering Selectors: - If a `RequestComponentSelector` does not support error rendering, it should re-raise the received `error` if it is not `None`. Failure to do so will not break core functionality as results and errors are separated, but it is considered good practice. - Custom Integrations: - Add the required generic type to `ComponentSelector` type hints when creating custom integrations to ensure compatibility with the new exception handling mechanisms. ``` -------------------------------- ### Jinja2 Loop: Display User Full Names Source: https://github.com/volfpeter/fasthx/blob/main/examples/jinja-rendering/templates/user-list.html This Jinja2 template iterates through a collection named 'items'. For each item, it accesses 'first_name' and 'last_name' attributes and formats them into a bulleted list entry with the user's full name. It's commonly used in web frameworks for dynamic content generation. ```Jinja2 {% for user in items %} * {{user.first_name}} {{user.last_name}} {% endfor %} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.