pythonpy-shiny

How to make a clickable URL in Shiny for Python?


I tried this:

app_ui = ui.page_fluid(
                ui.output_text("the_txt")
            )

def server(input, output, session):
    @render.text
    def the_txt():
        url = 'https://stackoverflow.com'
        clickable_url = f'<a> href="{url}" target="_blank">Click here</a>'
        return ui.HTML(clickable_url)

But the displayed text is the raw HTML: <a> href="https://stackoverflow.com" target="_blank">Click here</a>

How do I display a clickable link in a Shiny for Python app?


Solution

  • In your app you have a small syntax error within the tag, you need <a ...> instead of <a> .... Below are two variants, depending on a static case or a situation where you have to render something.

    Static case

    You don't need a render function here since this is only HTML. Below are two alternatives: Either use ui.tags for creating an a tag or use ui.HTML for passing the HTML directly:

    from shiny import ui, App
    
    url = 'https://stackoverflow.com'
    
    app_ui = ui.page_fluid(
        ui.tags.a("Click here",
                  href=url,
                  target='_blank'),
        ui.p(),
        ui.HTML(f'<a href="{url}" target="_blank">Click here</a>')
    )
    
    def server(input, output, session):
        return
    
    app=App(app_ui, server)
    

    enter image description here

    Dynamic case

    Here is an example where we have an input and render a link dynamically into a text. The output here is set by ui.output_ui and contains a div with the text and the url.

    from shiny import ui, App, render, reactive
    
    app_ui = ui.page_fluid(
        ui.input_select("pageSelect",
                        label="Pages",
                        choices=['StackOverflow', 'Google']),
        ui.p(),
        ui.output_ui("text")
    )
    
    def server(input, output, session):
        
        @reactive.calc
        def url():
            if (input.pageSelect() == "StackOverflow"):
                url = 'https://stackoverflow.com'
            else: 
                url = 'https://google.com'
            return ui.tags.a("click here", href=url, target='_blank')
        
        @render.ui
        def text(): 
            return ui.div("You can ", 
                          url(), 
                          " for going to ", 
                          input.pageSelect(),
                          ".")
    
    app=App(app_ui, server)
    

    enter image description here