module.server

module.server(fn)

Decorator for defining a Shiny module server function.

This decorator is used to encapsulate the server logic for a Shiny module. It automatically creates a namespaced child Session using the provided module id, and passes the appropriate input, output, and session objects to your server function.

This ensures that the server logic is scoped correctly for each module instance and allows for reuse of logic across multiple instances of the same module.

Parameters

fn : Callable[Concatenate[Inputs, Outputs, Session, P], R]

A server function that takes input, output, and session as its first three arguments, followed by any additional arguments defined by the user.

Returns

: Callable[Concatenate[str, P], R]

A function that takes a module id (as a string) as its first argument, followed by any arguments expected by fn. When called, it will register the module’s server logic in a namespaced context.

See Also

Examples

#| standalone: true
#| components: [editor, viewer]
#| layout: vertical
#| viewerHeight: 400

## file: app.py
from shiny import App, Inputs, Outputs, Session, module, reactive, render, ui


# ============================================================
# Counter module
# ============================================================
@module.ui
def counter_ui(label: str = "Increment counter") -> ui.TagChild:
    return ui.card(
        ui.h2("This is " + label),
        ui.input_action_button(id="button", label=label),
        ui.output_text(id="out"),
    )


@module.server
def counter_server(
    input: Inputs, output: Outputs, session: Session, starting_value: int = 0
):
    count: reactive.value[int] = reactive.value(starting_value)

    @reactive.effect
    @reactive.event(input.button)
    def _():
        count.set(count() + 1)

    @render.text
    def out() -> str:
        return f"Click count is {count()}"


# =============================================================================
# App that uses module
# =============================================================================
app_ui = ui.page_fluid(
    counter_ui("counter1", "Counter 1"),
    counter_ui("counter2", "Counter 2"),
)


def server(input: Inputs, output: Outputs, session: Session):
    counter_server("counter1")
    counter_server("counter2")


app = App(app_ui, server)