Load CSS file and HTML fragment using official way

What is a better way or the official way to load CSS file and HTML fragment?

Below is what I do:

main.py


def load_css(file_path):
    with open(file_path, "r") as css_file:
        st.markdown(f'<style>{css_file.read()}</style>', unsafe_allow_html=True)

def load_html(file_path):
    with open(file_path, "r") as html_file:
        st.markdown(html_file.read(), unsafe_allow_html=True)

load_css("./css/style.css")
load_html("./html_fragment/header.html")

header.html
<header>APPs Header</header>

style.css

.test {
    color: red
}

If the above is the best way, may I ask how to fix the two load methods? Currently the two methods cannot load files when all three files are not in the root folder.

You can use html instead of markdown. I am not sure how or even if they handle HTML differently.

Both methods seem to work for me regardless of where the files are located, as long as the app can read them.

What about loading html using the function load_html()?

Is there a better way for CSS and HTML fragment? For example, using Fragment or other Streamlit built-in features?

Your example works for me.

Define better. What do you think is wrong with your code above?

As @Goyo suggested, st.html will likely be cleaner. You don’t need to define a function to read the contents of a file then populate the frontend; st.html can accept a file path.

You can replace:

def load_html(file_path):
    with open(file_path, "r") as html_file:
        st.markdown(html_file.read(), unsafe_allow_html=True)
load_html("./html_fragment/header.html")

with just:

st.html("./html_fragment/header.html")

What are you trying to accomplish specifically with a fragment?

Does st.html use caching?

Using Fragment to load CSS or HTML fragment, or adding caching if possible.

No, st.html doesn’t have caching, but neither does fragments. You can certainly define a function and add caching so that it’s not rereading from the file and instead pulls from memory, but I’m not understanding what you’d get out of fragments here. Are your HTML and CSS files changing? If you just have static HTML/CSS files, I’m not sure how much benefit you’ll get from caching.