How can I learn what Page I am looking at

I have seen What is the current page in use? Multipage App - :balloon: Using Streamlit - Streamlit and have searched pretty extensively online but have the same question as the poster there: How can I programmatically determine what page I am looking at? Importantly, st_javascript and other JavaScript-based solutions, like others have noted, make the page run twice, which is potentially opening up a rabbit hole of issues for us.

Like the poster there noted, you can use st.set_page_config() to set the page title… is there truly no clean way to get the page title?

@blackary, maybe you know? I am using st-pages if that helps. @Goyo you have been helpful in the past as well if you had an idea.

Thanks very much in advance!

I don’t get it. If you are calling st.set_page_config to set the page title then you already know what the page title is. What problem is there to solve?

You can use some of the code that st_pages uses to set the page title:

# Note that you can also import these from streamlit directly
from st_pages import get_pages, get_script_run_ctx 

pages = get_pages("")
ctx = get_script_run_ctx()

try:
    current_page = pages[ctx.page_script_hash]
except KeyError:
    current_page = [
        p for p in pages.values() if p["relative_page_hash"] == ctx.page_script_hash
    ][0]


st.write("Current page:", current_page)
2 Likes

Thanks so much to you both for your fast responses!

@Goyo The primary problem is that st.data_editor() does not preserve its state when switching between pages in multi-page apps and one solution, such as the one here, is improved by only performing certain actions when the user has changed pages. So the app needs to know when the user has switched pages.

@blackary Your solution works great! Importantly, no re-running of the script! I have implemented it in the tool I mentioned above, linked here, and credited you for it.

Quick question about your comment @blackary (“Note that you can also import these from streamlit directly”): How can I do that, and is one method of importing advantageous over the other?

Thanks again!

1 Like

@andrew-weisman The tricky part about importing these from streamlit is that the exact locations of these functions has changed over time (and may well change again), because they’re not really supposed to be used this way :slight_smile:

You can see how st_pages imports them from Streamlit here: https://github.com/blackary/st_pages/blob/main/src/st_pages/__init__.py#L24-L31

That exact code should work fine, but it’s much shorter to import from st_pages and avoid the try…except…

1 Like

Ah I see @blackary, thanks for the information and for putting the work in to abstract those changing locations away from st_pages where the functionality is more stable! Your solution is working great by the way, thanks again.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.