skip to Main Content

When I create the following dash app, the goal is to have each element included in the output from the callback display on a new line. However, when I run the app, each element is displayed on the same line. Images of the current output vs. desired output are imbedded after the code snippet.

Please share a solution and an explanation of why my code isn’t providing the desired results:

app = Dash(__name__)

app.layout = html.Div([
    dcc.Dropdown(
        id = 'dd_input', 
        options = ['test1', 'test2', 'test3'], 
        value = ['test1', 'test2'],
        multi = True
        ),
    html.P(
        id = 'string_output'
        ) 
])

@callback(
    Output('string_output', 'children'), 
    Input('dd_input','value')
)

def test_func(dd_choice):
    string = ''
    new_line = 'n'
    
    for each in dd_choice:
        string += f'{each}{new_line}'
        
    return string
                       
if __name__ == '__main__':
    app.run(debug = True)

This is the output I keep getting that I DO NOT want:

enter image description here

The following is the desired output:

enter image description here

Attempts using append and join methods as suggested by stack responses. These solutions do not work:

enter image description here

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    Thank you to everyone... for forcing me to find an answer...to my own question.

    You append each string to a list and then add the dash html.Br component after each string in the list. Then you simply return the list after your loop has completed:

    app = Dash(__name__)
    
    app.layout = html.Div([
        dcc.Dropdown(
            id = 'dd_input', 
            options = ['test1', 'test2', 'test3'], 
            value = ['test1', 'test2'],
            multi = True
            ),
        html.P(
            id = 'string_output'
            ) 
    ])
    
    @callback(
        Output('string_output', 'children'), 
        Input('dd_input','value')
    )
    
    def test_func(dd_choice):
        string = ''
        new_line = html.Br() # dash html component
        lst = [] # empty list
    
        for each in dd_choice:
            string = f'{each}'
    
            lst.append(string) # add string to list
    
            lst.append(new_line) # add line break after each string
    
        return lst
    
    if __name__ == '__main__':
        app.run(debug = True)
    

    enter image description here


  2. Like as Barmar said, you need use <br> for line break.
    Try to use this:

    ...
    from dash import html
    ...
    for each in dd_choice:
        string.append(each)
    return html.Br().join(string)
    ...
    

    source: https://dash.plotly.com/dash-html-components/br

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search