Plotly Dash: Display a variable inside Markdown text

Viewed 2749

I'm new to the Dash and Plotly ecosystem and began building a web-based dashboard a few days ago.

Here is a snippet of code:

import dash
import dash_html_components as html
import dash_core_components as dcc


# initialize the application
app = dash.Dash()

# define the layout of the app
app.layout = html.Div([

# add a date range selector
dcc.DatePickerRange(
    id = 'my-date-picker-range',
    min_date_allowed = dt(2010,1,4),
    max_date_allowed = dt(2020, 12, 31),
    initial_visible_month = dt(2020, 5, 23)
),

html.Div(id = 'output-container-date-picker-range'),

# add some markdown text
dcc.Markdown(f'''
    This report covers the time period spanning {start_date} to {end_date}.
    '''),

])


@app.callback(
    dash.dependencies.Output('output-container-date-picker-range', 'children'),
    [dash.dependencies.Input('my-date-picker-range', 'start_date'),
     dash.dependencies.Input('my-date-picker-range', 'end_date')])

app.run_server(debug = True)

I'm attempting to display the start_date and end_date variables inside the markdown text (using an f string). Unfortunately, I'm getting the following error message:

NameError: name 'start_date' is not defined

Is it possible to include variable output in Markdown text? Thanks!

1 Answers

You are using a decorator (@app.callback) but you did not attach it to a function to be executed. You need to attach the decorator to the function that is responsible for updating the right div.

I think your best bet is to stick to the documentation.

This gives a similar result as what you want:

import dash
import dash_html_components as html
import dash_core_components as dcc
from datetime import datetime as dt

# initialize the application
app = dash.Dash()

# define the layout of the app
app.layout = html.Div([

    # add a date range selector
    dcc.DatePickerRange(
        id = 'my-date-picker-range',
        min_date_allowed = dt(2010,1,4),
        max_date_allowed = dt(2020, 12, 31),
        initial_visible_month = dt(2020, 5, 23)
    ),

    html.Div(id = 'output-container-date-picker-range'),
])

@app.callback(
    dash.dependencies.Output('output-container-date-picker-range', 'children'),
    [dash.dependencies.Input('my-date-picker-range', 'start_date'),
     dash.dependencies.Input('my-date-picker-range', 'end_date')])
def update_output_div(start_date, end_date):
    return f"This report covers the time period spanning {start_date} to {end_date}"

app.run_server(debug = True)
Related