如何在Shiny主应用app.py中调用外部文件的导航面板?
解决Shiny应用拆分导航面板的问题
要把page.py中的导航面板集成到app.py的navset_hidden中,核心是把外部面板的代码封装成可调用的函数,在主应用的导航上下文里执行,具体步骤如下:
修改page.py
将导航面板代码封装为函数,避免模块导入时直接创建面板(此时主导航上下文尚未建立,无法关联):
from shiny import reactive, render, req, ui from shiny.express import input, ui def other_page_panel(): with ui.nav_panel("Page I want to put in the main app", value="other_page"): @render.express def filler_text(): "Filler text"
修改app.py
在主导航的with块内调用page.py中定义的函数,将外部面板添加到主导航集合里:
from shiny import reactive, render, req, ui from shiny.express import input, ui import page with ui.navset_hidden(id="selected_navset_tab"): # Homepage with ui.nav_panel("Welcome", value="page_home"): with ui.card(): ui.input_selectize( "filler", "Filler", ["list", "of", "items", "here"], multiple=False ) # 导入并添加外部导航面板 page.other_page_panel()
原理说明
直接在page.py中使用with ui.nav_panel会在模块导入阶段执行,此时主应用的navset_hidden上下文还没激活,面板无法被正确关联到主导航集合。封装成函数后,在navset_hidden的with块内调用函数,函数内部的with ui.nav_panel会在主导航的上下文环境中执行,从而将面板正确集成到主应用里。
内容的提问来源于stack exchange,提问作者Redz
相关产品推荐
相关产品推荐

