taipy

How to update Taipy page on button click


I have ben trying add elements to the taipy page on button click. Whenever the add button is clicked the add_element function is called which is suppossed to add an input field to the web page. Please does any one know the right code/syntax for this ? Here is my code bellow.


import taipy as tp
import taipy.gui.builder as tgb
from taipy import Gui, Config, Core
from taipy.gui import Markdown


input_name = "Taipy"
message = None


with tgb.Page() as page:
    tgb.input("{input_name}")
    tgb.text("{message}")
    tgb.button("add" , on_action='add_element')


def add_element(state):
    page.add(tgb.input())


Gui(page).run()


Solution

  • This type of function does not exist in Taipy at the moment. However, you can update the page on the fly.

    Partials

    You have the option in Taipy to use partials. They are blocks of content that can be modified/reloaded dynamically. For the moment, they use the Markdown syntax to be updated:

    import taipy.gui.builder as tgb
    from taipy import Gui
    
    
    input_name = "Taipy"
    message = None
    
    
    with tgb.Page() as page:
        tgb.input("{input_name}")
        tgb.text("{message}")
        tgb.button("add" , on_action='add_element')
        tgb.part(partial='{dynamic_content}')
    
    
    def add_element(state):
        state.dynamic_content.update_content(state, '<|input|>')
    
    
    gui = Gui(page)
    dynamic_content = gui.add_partial('')
    gui.run()
    

    We want to improve the integration between Markdown and Python to make pages more dynamic and in an easier way (see issue).

    Render

    However, we recommend using the render feature of part to render or not a part of your page. This approach is better regarding best practices as it is easier to understand and you have no part of your page reloaded in runtime, but it is only sometimes possible.

    import taipy.gui.builder as tgb
    from taipy import Gui
    
    
    input_name = "Taipy"
    message = None
    input_rendered = False
    
    with tgb.Page() as page:
        tgb.input("{input_name}")
        tgb.text("{message}")
        tgb.button("add", on_action='add_element')
        with tgb.part(render='{input_rendered}'):
            tgb.input()
    
    
    def add_element(state):
        state.input_rendered = True
    
    Gui(page).run()