Webapp HTML/Python

MathieuS
MathieuS Registered Posts: 2 ✭✭✭

Hi,

Is there any way to update a text label in a webapp (created in HTML tab) with a variable resulting from a python function ?

In the same way, I would be interested to fill a Select component in HTML tab based on a python list.

I saw that it's possible to get acess to html values in backend using JS but i didn't find out how to do it in the reverse way

Thanks,

Mathieu

Tagged:

Best Answer

  • HenriC
    HenriC Dataiker Posts: 22 Dataiker
    edited July 17 Answer ✓

    Hi @MathieuS
    and thanks for using the Community

    There are many ways of doing what you say. Here is one very easy way that you can use by adapting it to your use case :

    HTML

    <div>
        <h1 id="label"></h1>
        <select id="select"></select>
    </div>

    JavaScript

    // We call a backend Python route that will return data in which is the label
    $.getJSON(getWebAppBackendUrl('/get-updated-label'), function(data) {
        $('#label').text(data.label)
    });
    
    $.getJSON(getWebAppBackendUrl('/get-select-options'), function(data) {
        data.forEach((x) => {
            // For each option, we add it to the select
            $('#select').append(new Option(x.label, x.value));
        })
    });
    

    Python

    @app.route('/get-updated-label')
    def updated_label():
        return json.dumps({"label": "New Label"})
    
    
    @app.route('/get-select-options')
    def select_options():
        return json.dumps([
            {
                "label": "Option 1",
                "value": "option_1"
            },
            {
                "label": "Option 2",
                "value": "option_2"
            },
            {
                "label": "Option 3",
                "value": "option_3"
            },
            {
                "label": "Option 4",
                "value": "option_4"
            },
        ])
    

    You can use this code into a webapp that has Python backend enabled.

    Do not hesitate if you do not understand something or need more help!

    Henri

Answers

Setup Info
    Tags
      Help me…