pythontaipy

How to create multi-page app with each page on a separate module


This is my main.py file where I have defined a module for each page:

from taipy import Gui
import taipy.gui.builder as tgb

# Import your page constructors
from pages.home import get_home_page
from pages.about import get_about_page
from pages.root import get_root_page
from pages.initial_setup import get_initial_setup_page

if __name__ == "__main__":

    # Instantiate pages from their modules
    home_page = get_home_page()
    about_page = get_about_page()
    root_page = get_root_page()
    initial_setup_page = get_initial_setup_page()

    pages = {
        "/": root_page,
        "home": home_page,
        "about": about_page,
        "Initial-Setup": initial_setup_page,
    }

    Gui(pages=pages).run(host="0.0.0.0", use_reloader=True, debug=True, port=5000)

and this is how I am trying to implement the page in a separate module:

import taipy.gui.builder as tgb

def get_home_page():
    with tgb.Page() as page:
        tgb.text("# Welcome to Home", mode="md")
    return page

Any better approach? To help keep the page sessions in tact as well

Any better approach? To help keep the page sessions in tact as well


Solution

  • This is almost right. You just have to instantiate the page directly in the script and not inside a function. And import the page in the main.py, not the function. You can define your callbacks and variables there like you would do in the main.py. Check this demo for an example: https://github.com/Avaiga/demo-covid-dashboard/tree/develop/src_tgb

    from taipy import Gui
    import taipy.gui.builder as tgb
    
    # Import your page constructors
    from pages.home import home_page
    from pages.about import about_page
    from pages.root import root_page
    from pages.initial_setup import initial_setup_page
    
    if __name__ == "__main__":
        pages = {
            "/": root_page,
            "home": home_page,
            "about": about_page,
            "Initial-Setup": initial_setup_page,
        }
    
        Gui(pages=pages).run(host="0.0.0.0", use_reloader=True, debug=True, port=5000)
    

    Taipy will create a scope for a page defined in a module so that you have variables with the same name in different pages with different values. If you want to share these variables, they should be defined or imported in the main.py. You could also look into the root page, a page that is common to every page.

    import taipy.gui.builder as tgb
    
    
    with tgb.Page() as <name>_page:
        tgb.text("# Welcome to Home", mode="md")