banner

Streamlit apps can be both functional and beautiful. By combining the basics of HTML with Streamlit’s advanced features, you can customize your apps to make them unique, attractive, and powerful. Explore the fundamentals of HTML and discover how to render it within your Streamlit applications for maximum effect.

Introduction to HTML Rendering in Streamlit

Streamlit allows developers to render HTML directly within the app, unlocking a powerful and unique way of customizing apps. Through HTML tags and attributes, it is possible to completely tailor the look and feel of your app to be exactly how you want it. From simple styling tweaks to comprehensive structural changes, HTML rendering provides an amazing array of options.

import streamlit as st

st.title("My Streamlit App")
st.write("This is some regular text.")

# Rendering HTML in Streamlit
st.write("This is <b>bold</b> text, and this is <em>italicized</em> text.")

Understanding the Basics of the Streamlit Layout Model

The Streamlit layout model allows developers to quickly and easily create complex user interfaces with a few lines of code. By changing the parent structure for components, you can create hierarchical and structured apps that remain compliant with the underlying HTML standards. Understanding this layering effect will allow you to accurately map out how your app should look, which is crucial for enabling detailed customization through HTML rendering.

The main idea behind the Streamlit layout model is that components are organized into a parent-child relationship, with each component’s parents dictating its size and position. For example, if you were to define two columns using streamlit.columns(), then the components you place within will be organized in a two-column HTML table, with each column div taking up 50% of the page width. Components can also appear one after the other within their parents, lining up from left to right in order of appearance. Using this information about how the Streamlit elements are rendered in HTML, you can then begin customizing your app by injecting additional HTML code where needed for specific visual effects. In doing so you will have more control over the design and display of your Firebase Streamlit apps.

Customizing Your App Elements with HTML

Streamlit components can be customized through the use of HTML tags. These will modify the underlying st elements, allowing you to quickly and easily change how your app looks and functions. Modifying an element’s padding, background-color, or font family is as simple as adding an appropriate line to your Streamlit script. And since scripting languages are written in HTML, any complex changes can also be achieved.

Streamlit components can also be further modified with various HTML attributes. For example, if you want to increase the size of a st.textbox element, simply use the ‘width=’ attribute. To make your panel headings stand out more amidst the other content, you can use the ‘style=’ attribute to change its font color, size, and typeface. Or if you want to add more interaction to your app with an active drop-down box and radio buttons, consider utilizing, , and HTML tags. With a few strategic HTML additions and modifications anytime text or elements are created in Streamlit, you can quickly customize any page of your application.

import streamlit as st

# Customizing a text element with HTML tags
st.write("<p style='color: red;'>This text is red.</p>")

# Customizing an st.text_input element with an HTML attribute
st.text_input("Enter your name:", value="", max_chars=10, key=None, type="default", width=None, height=None, help=None, placeholder="Your name", autocomplete=None, autofocus=False, readonly=False, required=False, pattern=None, clear_on_submit=True, on_change=None, on_submit=None, on_key_down=None, on_key_up=None, args=None, kwargs=None, **_kwargs)

With HTML tags we can also hide the “made with streamlit” text at the footer

hide_streamlit_style = """           <style>           #MainMenu {visibility: hidden;}           footer {visibility: hidden;}           </style>           """st.markdown(hide_streamlit_style, unsafe_allow_html=True)

Styling Your App with External CSS

Advanced Streamlit developers may also want to include external style sheets (CSS) to their apps. By using style sheets, they can create a more uniform and consistent design across multiple pages and apps. External CSS files are incredibly useful even for simple changes like setting the font-family or background color of the app. This ensures that your Streamlit app always looks its best!

To include an external style sheet, you must use the `st.markdown` command and add the CSS file as a link in the text. You can experiment with streams of HTML commands to craft a beautiful design for your Streamlit app, then save it in an external style sheet. Then whenever you need to modify the styling of your app, all you have to do is update the file and save it — no need to go through the Streamlit components again. This makes styling your Streamlit apps fast and easy so that you have more time to focus on writing code and building thoughtful web apps!

import streamlit as st

# Include an external style sheet
st.markdown("<link rel='stylesheet' href='styles.css'>", unsafe_allow_html=True)
or
with open("assets/style.css") as f:       st.markdown(f'<style>{f.read()}</style>',unsafe_allow_html=True)

Rendering HTML Files in Streamlit 

One of the powerful features of Streamlit is its ability to use third-party components to extend its functionality. These components are developed and maintained by the Streamlit community, and they offer a wider range of customizations.

One such component is the components.html module. This module allows you to render and display the entire HTML file within a Streamlit app. You can use this module to incorporate complex HTML structures into your application, including forms, tables, and charts.

Additionally, the components.html module can be paired with the Jinja2 template engine to pass data from Python, render the HTML, and then display the final HTML file on the app. This enables you to create dynamic HTML pages that can update based on user inputs or data changes.

from jinja2 import Template

def render_table(data):
               with open("templates/table.html") as table:
                   template = Template(table.read())
                   return template.render(
                       data=data
               )
<table>

   <thead>

       <th>Col1</th> 

       <th> Col2</th> 

   </thead>

   <tbody>

   {% for i in data -%}

     <tr>

       <td>{{i[0]}}</td> 

       <td>{{i[1]}}</td>

     </tr>

   {% endfor -%}

   </tbody>

 </table>
import streamlit.components.v1 as components

table = render_table(data=data)
components.html(table)

Incorporating JavaScript for Enhanced Functionality

Another powerful way to customize your Streamlit app is by incorporating JavaScript. Streamlit apps run on the web, so even basic operations like validating user input or reacting to user actions can be implemented using JavaScript. Plus, there are plenty of frontend libraries and frameworks that you can use as well, such as React and Vue.js. Incorporating JavaScript into your app unlocks massive potential for a better user experience, including advanced features like drag-and-drop interfaces and complex custom animations.

When adding JavaScript to your Streamlit app, you’ll likely start by adding it directly into the HTML file. Streamlit uses the Jinja2 templating language to render HTML files, which makes it easy to incorporate elements like JavaScript libraries and referenced functions into the rendered output. From there, you can begin adding custom features that react to user actions and store data in their browser session.

import streamlit as st

# Add a script tag to include external JavaScript
st.markdown("<script src='myscript.js'></script>", unsafe_allow_html=True)

# Use JavaScript to validate user input on a text input element
st.text_input("Enter your age:", max_chars=2, type="number", key=None, help="Please enter your age.")

age = st.session_state.get("age", None)

if age is not None and age < 18:
    st.warning("You must be at least 18 years old to use this app.")
else:
    st.success("Welcome to our app!")

it is impossible to overlook the usefulness and usability of apps in today’s fast-paced world! Apps keep us engaged the whole day & their significance can be listed in all A-Z categories. 

To build a web app programmers typically use Python web frameworks such as Django and Flask, which are considered the gold standard. But the steep learning curve, technical barriers, and the time investment in implementing these steps act as major hurdles. 

Low-code solutions such as Streamlit have lowered such barriers and enabled data enthusiasts to easily convert machine-learning models into interactive web apps. 

Streamlit makes the job of Machine Learning engineers so much easier without the need for a Web development team. App development can now be done in a faster & more efficient way! This open-source app framework uses the Python language & helps to create web apps for data science & machine learning within a concise time period.  

Streamlit imports the HTML file as a component and displays it in the app. If the programmer’s goal is to create a Streamlit Component solely to display HTML code or render a chart from a Python visualization library, Streamlit incorporates two methods that simplify this process: components.html() and components.iframe(). 

Users can view and operate app features with ease. Now with Streamlit, building apps are as simple as writing Python scripts. Streamlit also enables the user-specific customization of modules using effortless API integration.

Workflow of Streamlit Apps

Streamlit is a popular open-source framework that allows developers to quickly create and deploy data-driven apps with Python. The framework is designed to be simple and intuitive, allowing developers to focus on building the application rather than spending time on infrastructure.

The workflow of a typical Streamlit app can be broken down into the following steps:

  1. Data preparation: In this step, the developer prepares the data that will be used in the app. This can include loading data from various sources, cleaning and transforming the data, and creating any necessary data structures.
  2. App design: The next step is to design the app using Streamlit’s various components. These components include sliders, buttons, text inputs, and visualizations. The developer can choose from a wide range of components to create an interactive and engaging user interface.
  3. App logic: Once the app design is complete, the developer can write the app logic in Python. This includes defining the various functions and calculations that will be used in the app. Streamlit makes it easy to update the app in real-time as the user interacts with it.
  4. Deployment: The final step is to deploy the app. Streamlit provides various deployment options, including sharing the app on Streamlit’s cloud platform or deploying it on a server using Docker or Kubernetes.

Overall, Streamlit offers a streamlined and intuitive workflow for developing data-driven apps with Python. The framework’s simplicity and flexibility make it a popular choice for developers looking to quickly build and deploy data-driven apps.

Leave a Reply

Your email address will not be published. Required fields are marked *