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)Relevant Functions
-
ui.output_code
ui.output_code(id, placeholder=True) -
@render.code
render.code(_fn=None, *, placeholder=True)
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:
Add
ui.output_code()to the UI, passing it a uniqueid.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.Decorate the function with
@render.codeand give it the same name as the outputid. 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.