Toggle Sidebar

Dear experts,

I am creating a application that uses a sidebar, initialised as:

st.set_page_config(
    page_title="AutoDQM GUI",
    page_icon="assets/cms_favicon.png",
    layout="wide",
    initial_sidebar_state="expanded",
    menu_items={
        'Get Help': 'https://www.google.com',
        'Report a bug': "https://www.google.com",
        'About': "CMS AutoDQM application for offline DQM certification."
    }
)

And I can hide and unhide it in the GUI without any problems.

But, I also need to be able in my code to hide ir or unhide it from inside the python code, something like:

if condition:
     hide sidebar
elif condition_2:
    unhide sidebar
else:
   ...

Is it possible to do this?

Best,
Caio

Sort of. Just like st.expander your Streamlit server only knows the initial state of the sidebar. The opening or closing of the sidebar for the GUI is only known to the frontend. In order to forcibly rerender the sidebar, you have to change the initial state so Streamlit considers it to be “different.” That means you may need a little trick to render the sidebar the opposite of how you want, then quickly rerun the app to force it into the desired state.

Here’s a thread discussing the cycling through states needed for st.expander: Closing current expander and opening next by button-press - #10 by mathcatsand