Code

#| '!! shinylive warning !!': |
#|   shinylive does not work in self-contained HTML documents.
#|   Please set `embed-resources: false` in your metadata.
#| standalone: true
#| components: [viewer]
#| viewerHeight: 200

from shiny import App, render, ui

app_ui = ui.page_fluid(
    ui.input_text("message", "Message", "Hello Shiny"),
    ui.output_code("code"),
    class_="px-3 pt-3",
)

def server(input, output, session):
    @render.code
    def code():
        return f'print("{input.message()}")'

app = App(app_ui, server)
from shiny.express import input, render, ui

ui.input_text("message", "Message", "Hello Shiny")

@render.code  
def code():
    return f'print("{input.message()}")'
from shiny import App, render, ui

app_ui = ui.page_fluid(
    ui.input_text("message", "Message", "Hello Shiny"),
    ui.output_code("code"),  
)

def server(input, output, session):
    @render.code  
    def code():
        return f'print("{input.message()}")'

app = App(app_ui, server)
No matching items

Relevant Functions

No matching items

Details

A code output displays a character string as monospaced code in a shaded rectangle. It is the recommended way to show code, log output, or any other text where whitespace and line breaks matter.

To make reactive code output, follow three steps:

  1. Add ui.output_code() to the UI, passing it a unique id.

  2. Define a function in the server that returns the string to display. The string is shown exactly as returned, so use \n (or a triple-quoted string) for line breaks.

  3. Decorate the function with @render.code and give it the same name as the output id. Shiny matches the two by name.

By default, ui.output_code() displays an empty shaded rectangle as a placeholder even when the string to display is empty. To hide the rectangle when the string is empty, set placeholder=False.

See also: Verbatim Text and Text for other ways to display text output, and Code Editor for letting the user write code rather than read it.