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.
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?
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.
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.