How to give bg color to specific text within a string - returned from callback

I have a dictionary with values to be printed in a div

html.Div([html.P(id=‘my_info’,children=)]

div value is returned from a callback as

info_display = "[ Score: " + str(np.round(my_info[‘score’],2)) + " ] [State : " + {-1:‘OFF’,0:‘NONE’,1:‘ON’}[my_info[‘state’]] + " ] [Change " + str(my_info[‘change’]) + " ] "

Is it possible using dash ; No of text to display can vary

Hi @yogi_dhiman, something like this?

import numpy as np
from dash import Dash, Input, Output, html
from dash.exceptions import PreventUpdate

app = Dash(__name__)

app.layout = html.Div(
    [
        html.Button(
            'create value',
            id='btn'
        ),
        html.Div(id='dump')

    ]
)


@app.callback(
    Output('dump', 'children'),
    Input('btn', 'n_clicks'),
)
def start_interval(click):
    if not click:
        raise PreventUpdate
   
 value = np.random.randint(-5, 5)
    return html.Div(
        value,
        style={
            'height': '60px',
            'width': '60px',
            'background-color': ['green', 'red'][value < 0],
            'font-size': 60,
            'text-align': 'center',

        }
    )


if __name__ == "__main__":
    app.run(debug=True)

colors

Thanks for quick reply Aimped

as per your example your return is 4 but i want to return 4 3 -1 ( as string )

my_dict = {0:4,1:3,2:-1}
value = str(my_dict[0]) + str(my_dict[1]) + str(my_dict[2])

then outcome is
“4 3 -1”
bg color of 4 ( red) , bg color of 3 green , and bg color of -1 red

can have multiple html.p or html.span as return within div that stores each key of dict

1 Like

Hi @yogi_dhiman, why would have “4” a red background? What is the underlying logic? Up to now I thought, a negative value gets a red background. The following code would do this:

import numpy as np
from dash import Dash, Input, Output, html
from dash.exceptions import PreventUpdate

app = Dash(__name__)

app.layout = html.Div(
    [
        html.Button(
            'create value',
            id='btn'
        ),
        html.Div(id='dump')

    ]
)


@app.callback(
    Output('dump', 'children'),
    Input('btn', 'n_clicks'),
)
def start_interval(click):
    if not click:
        raise PreventUpdate
    
    my_dict = {0: 4, 1: 3, 2: -1}
    return create_div(my_dict)


def create_div(my_dict):
    out = [
        html.Span(
            content,
            style={
                'height': '60px',
                'background-color': ['green', 'red'][content < 0],
                'font-size': 60,
                'text-align': 'center',
            },
        ) for content in my_dict.values()
    ]
    return out


if __name__ == "__main__":
    app.run(debug=True)

grafik
mred layout

2 Likes

Its just based on sign of the value ; your assumption is correct
and you saved my day

2 Likes