code
A code snippet with syntax highlighting and a copy button.
Preview
Live preview
app.pyPython
import dyui
from dyui import ui
app = dyui.App(title="Travel Bot", accent="indigo")
@app.on_message
async def reply(msg: dyui.Message, chat: dyui.Chat):
yield "Here are two options:"
yield ui.Stat("Cheapest", "$189", delta="-12%", trend="down")
Usage
Inside a handler (@app.on_message, @app.on_action…), yield it or pass it to chat.send(). This is a fragment. The complete example below is a whole file you can run.
# inside a handler: @app.on_message, @app.on_action, ...yield ui.Code("pip install dyui", language="bash")Inside a reply, the model writes one JSON object per line in a dyui fence. DyUI validates it with the same pydantic model.
```dyui{"ui":"code","code":"pip install dyui","language":"bash"}```This is the line DyUI adds to the system prompt for this component. dyui catalog app.py prints the whole section.
code(code: string, language?: string, filename?: string) — A code snippet with syntax highlighting and a copy button.Props
| Prop | Type | Default |
|---|---|---|
codepositional | string | required |
language | string | — |
filename | string | — |
In Python, code is accepted positionally.
Complete example
A whole app that shows code. It needs no API key.
"""A complete DyUI app that shows the `code` component.
Save it as app.py, then run: dyui run app.py"""import dyuifrom dyui import ui
app = dyui.App(title="Code demo", starters=["Show me"], persist=False)
@app.on_messageasync def reply(msg: dyui.Message, chat: dyui.Chat): yield "Here is the `code` component." yield ui.Code("pip install dyui", language="bash")- Save it as
app.pyin a new, empty folder, or download app.py. Paste it into an empty file: pasting below existing code joins the two. - Run it with
pip install dyui, thendyui run app.py. - Open http://localhost:8000 and tap Show me.
To let a model write it instead, stream a model with components=app.catalog; see Generative UI.