āœŠšŸæ Black Lives Matter. Please consider donating to Black Girls Code today.
šŸ‡ Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

How to optimize when you have several pages using the same layout?

I have a dashboard with two tabs. One, stock.py has one paragraph that change according to the selection.

from os.path import abspath, dirname
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from dash.dependencies import Input, Output
import pandas as pd
import requests
import yfinance as yf

from ..server import app

@app.callback(
    Output('sales', 'children'),
    [Input('select-stock', 'value')])
def update_earnings(entity):
    ticker = entity
    url = 'https://financialmodelingprep.com/'
    api = 'api/v3/financials/income-statement/'
    search_api_url = url + api + ticker
    response = requests.get(
        search_api_url
    )
    json = response.json()
    earnings = json['financials'][0]['Revenue']
    earnings = float(earnings)
    return '{:,.2f}'.format(earnings)

def layout():
    return html.Div([
        html.Div([
            html.Div([
                dcc.Dropdown(
                    id='select-stock',
                    options=STOCK_LIST,
                    value=STOCK_LIST[0].get('value')
                )
            ])
        ], className='pretty_container twelve columns'),
        html.Div([
            html.Div([
                html.H6('Sales', style={'textAlign': 'center', 'padding': 10}),
                html.P("Sales: ", id="sales", style={'textAlign': 'center', 'padding': 10})
            ], className='pretty_container four columns'),
        ]),
   ], className='pretty_container twelve columns')

if __name__ == "__main__":
    app.run_server(debug=False, port=8051)

The other one has a data-table that, when you click on one of the lines, a pop-up appears with the same paragraph.

import dash_table
import os
import pandas as pd
from dash.dependencies import Input, Output, State
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import requests

from ..server import app

# app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DATA_PATH = os.path.join(PROJECT_ROOT, '../data/')
df = pd.read_csv(DATA_PATH + 'tickers_september_2017_red.csv')


def layout():
    return html.Div([
        dash_table.DataTable(
            id='table',
            columns=[{"name": i, "id": i} for i in df.columns],
            data=df.to_dict('records'),

            # sort_action='custom',
            # sort_mode='single',
            # sort_by=[]
        ),
        dbc.Modal(
            [
                dbc.ModalHeader("Header", id="ModalHeader"),
                dbc.ModalBody("This is the content of the modal"),
                dbc.ModalFooter(
                    dbc.Button("Close", id="close", className="ml-auto")
                ),
            ],
            id="modal",
            size="xl",
        )
    ])


@app.callback(Output("modal", "children"),
              [Input('table', 'active_cell'),
              Input('close', 'n_clicks')],)
def set_content(active_cell, n_clicks):
    row = df.iloc[[active_cell.get("row")]]
    ticker = row['Name'].values[0]

    return [
        dbc.ModalHeader(row['Name'].values[0]),
        html.Div([
            html.Div([
                html.H6('Sales', style={'textAlign': 'center', 'padding': 10}),
                # html.P(update_earnings(ticker), id="sales", style={'textAlign': 'center', 'padding': 10})
                html.P("Sales: ", id="sales", style={'textAlign': 'center', 'padding': 10})
            ], className='pretty_container four columns'),
        ]),
        dbc.ModalFooter(dbc.Button("Close", id="close")),
    ]


def update_earnings(ticker):
    url = 'https://financialmodelingprep.com/'
    api = 'api/v3/financials/income-statement/'
    search_api_url = url + api + ticker
    response = requests.get(
        search_api_url
    )
    json = response.json()
    earnings = json['financials'][0]['Revenue']
    earnings = float(earnings)
    return '{:,.2f}'.format(earnings)


@app.callback(Output('modal', 'is_open'),
              [Input('table', 'active_cell'),
               Input('close', 'n_clicks')],
              [State("modal", "is_open")])
def toggle_modal(n1, n2, is_open):
    if n1 or n2:
        return not is_open
    return is_open


if __name__ == '__main__':
    app.run_server(debug=False, port=8051)

However I am coding the paragrah twice, one in stock.py and another time instocks.py. As Iā€™m planning the popups to have the exact same structure with those in stock.py. Is there a more optimized way to do so?