import os
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("""
# Simple HTML usecase
This is the classic `gr.HTML` usecase where we just want to render some static HTML.
""")
simple_html = gr.HTML("
Hello, World!
")
gr.Markdown("""
# Templated HTML usecase
'value' can now be anything, and it can be used inside the `html_template` using `${value}` syntax.
Note that when used as output or input, `value` is just this specific value rather than the entire HTML.
""")
with gr.Row():
name1 = gr.Textbox(label="Name")
templated_html = gr.HTML(
"",
html_template="
Hello, {{value}}! ${value.length} letters
",
elem_id="templated",
)
name1.change(lambda x: x, inputs=name1, outputs=templated_html)
gr.Markdown("""
# Additional Props
You are not limited to using `${value}` in the templates, you can add any number of custom tags to the template, and pass them to the component as keyword arguments. These props can be updated via python event listeners as well.
""")
with gr.Row():
templated_html_props = gr.HTML(
"John",
html_template="""
Hello, ${value}!
""",
fontSize=30,
elem_id="props",
)
slider = gr.Slider(10, 100, value=30, label="Font Size")
slider.change(
lambda x: gr.HTML(fontSize=x), inputs=slider, outputs=templated_html_props
)
gr.Markdown("""
# CSS Templating
We can also template CSS, which is automatically scoped to the component.
""")
with gr.Row():
name2 = gr.Textbox(label="Person")
color = gr.ColorPicker(label="Text Color", value="#00ff00")
bold = gr.Checkbox(label="Bold Text", value=True)
templated_html_css = gr.HTML(
["J", "o", "h", "n"],
html_template="""
Hello, ${value.join('')}!
{{#each value}}
{{this}}
{{/each}}
""",
css_template="""
h1, li {
color: ${color};
font-weight: ${bold ? 'bold' : 'normal'};
}
""",
color="green",
bold=True,
elem_id="css",
)
with gr.Row():
btn = gr.Button("Update HTML")
btn_blue = gr.Button("Make HTML Blue")
def update_templated_html_css(name, color, bold):
return gr.HTML(value=list(name), color=color, bold=bold)
btn.click(
update_templated_html_css,
inputs=[name2, color, bold],
outputs=templated_html_css,
)
btn_blue.click(lambda: gr.HTML(color="blue"), outputs=templated_html_css)
gr.Markdown("""
# JS Prop Updates
We can now trigger events from gr.HTML using event listeners in `js_on_load`. This script has access to `element` which refers to the parent element, and `trigger(event_name)` or `trigger(event_name, event_data)`, which can be used to dispatch events.
""")
button_set = gr.HTML(
html_template="""
""",
css_template="""
button {
padding: 10px;
background-color: red;
}
""",
js_on_load="""
const buttons = element.querySelectorAll('button');
buttons.forEach(button => {
button.addEventListener('click', () => {
trigger('click', {clicked: button.innerText});
});
});
""",
elem_id="button_set",
)
clicked_box = gr.Textbox(label="Clicked")
def on_button_click(evt: gr.EventData):
return evt.clicked
button_set.click(on_button_click, outputs=clicked_box)
gr.Markdown("""
# JS Prop Changes
You can also update `value` or any other prop of the component from JS using `props`, e.g., `props.value = "new value"` will update the `value` prop and re-render the HTML template.
""")
form = gr.HTML(
html_template="""
${value.length} letters
""",
js_on_load="""
const input = element.querySelector('input');
const submit_button = element.querySelector('button.submit');
const clear_button = element.querySelector('button.clear');
input.addEventListener('input', () => {
props.valid = input.value.length > 5;
props.value = input.value;
});
submit_button.addEventListener('click', () => {
trigger('submit');
});
clear_button.addEventListener('click', () => {
props.value = "";
props.valid = false;
trigger('clear');
});
""",
valid=False,
elem_id="form",
)
output_box = gr.Textbox(label="Output Box")
form.submit(lambda x: x, form, outputs=output_box)
output_box.submit(lambda x: x, output_box, outputs=form)
gr.Markdown("""
# Watch API
Use `watch` inside `js_on_load` to run a callback after the template re-renders whenever specific props are changed from the backend (Python event listener). The callback is NOT triggered by frontend (JavaScript) changes to props. The callback takes no arguments — read current values from `props` directly.
""")
watch_html = gr.HTML(
value=0,
html_template="""
value: ${value}
""",
js_on_load="""
watch('value', () => {
if (props.value >= 3) {
trigger('submit');
}
});
""",
elem_id="watch_demo",
)
watch_output = gr.Textbox(label="Watch Output")
watch_inc_btn = gr.Button("Increment")
watch_inc_btn.click(lambda x: (x or 0) + 1, watch_html, outputs=watch_html)
watch_html.submit(lambda x: x, watch_html, outputs=watch_output)
gr.Markdown("""
# Extending gr.HTML for new Components
You can create your own Components by extending the gr.HTML class.
""")
class ListComponent(gr.HTML):
def __init__(self, container=True, label="List", ordered=False, **kwargs):
self.ordered = ordered
super().__init__(
html_template="""
${label}
${ordered ? `` : `
`}
${value.map(item => `
${item}
`).join('')}
${ordered ? `
` : ``}
""",
container=container,
label=label,
ordered=ordered,
**kwargs,
)
l1 = ListComponent(
label="Fruits", value=["Apple", "Banana", "Cherry"], elem_id="fruits"
)
l2 = ListComponent(
label="Vegetables",
value=["Carrot", "Broccoli", "Spinach"],
elem_id="vegetables",
)
make_ordered_btn = gr.Button("Make Ordered")
make_unordered_btn = gr.Button("Make Unordered")
make_ordered_btn.click(
lambda: [ListComponent(ordered=True), ListComponent(ordered=True)],
outputs=[l1, l2],
)
make_unordered_btn.click(
lambda: [ListComponent(ordered=False), ListComponent(ordered=False)],
outputs=[l1, l2],
)
failed_template = gr.HTML(
value=None,
html_template="""
${Zalue}
""",
)
gr.Markdown("""
# File Upload via gr.HTML
The `upload` async function is available in `js_on_load`. It takes a JavaScript `File` object,
uploads it to the Gradio server, and returns the server-side file path as a string.
""")
upload_html = gr.HTML(
html_template="""