pythonpy-shiny

How to render a static SVG in Shiny for Python?


Is there a way to render a SVG in a shiny-python app directly rather than convert it to a png and then render it from an ImgData, by calling ui.output_plot?


Solution

  • Assuming your image is locally available, say img.svg, you could use render.image in combination with output.image like this:

    from shiny import App, Inputs, Outputs, Session, render, ui
    
    app_ui = ui.page_fluid(
        ui.output_image("image")
    )
    
    def server(input: Inputs, output: Outputs, session: Session):
        @render.image
        def image():
            from pathlib import Path
    
            dir = Path(__file__).resolve().parent
            img = {"src": str(dir / "img.svg")}
            return img
    
    app = App(app_ui, server)
    

    In Shiny Express you could use

    from shiny.express import render
    
    @render.image  
    def image():
        from pathlib import Path
        
        dir = Path(__file__).resolve().parent
        img = {"src": dir / "img.svg"}  
        return img