add static css files to nicegui

86 Views Asked by At

see also Global CSS stylesheet for NiceGUI

I have a bunch of local .css files i'd like to make available for ui.html() elements in nicegui. In justpy i used to do this as

  @self.app.route('/ceur-ws.css')
        def ceur_ws_css():
            return send_from_directory(f'{os.path.dirname(os.path.abspath(__file__))}/resources/css', "ceur-ws.css")

        @self.app.route('/ceur-ws-semantic.css')
        def ceur_ws_semantic_css():
            return send_from_directory(f'{os.path.dirname(os.path.abspath(__file__))}resources/css', 'ceur-ws-semantic.css')

What whould be the equivalent approach in nicegui? ther is e.g.

app.add_static_files('/examples', 'examples')

as described in https://nicegui.io/documentation/section_pages_routing

but that seems to force a new directory structure e.g. adding a "/css" to the links - since I want' to display contents in an iframe i don't have the option to modify the css access.

do I actually have to use

ui.add_head_html("<style>" + open(Path(__file__).parent / "static" / "styles.css").read() + "</style>")

e.g. in a loop?

1

There are 1 best solutions below

0
Falko On

It seems like app.add_static_file() (singular) could solve your problem. Its only mentioned briefly here:

To make a single file accessible, you can use add_static_file().

We use it, e.g., to serve the NiceGUI logo on our website:

app.add_static_file(local_file=svg.PATH / 'logo.png', url_path='/logo.png')
app.add_static_file(local_file=svg.PATH / 'logo_square.png', url_path='/logo_square.png')

https://github.com/zauberzeug/nicegui/blob/d2f6cede439417cff5ff635e14db0c4ae8e20fb9/main.py#L23-L24