Home > Software design >  How to use if statment inside div tags with streamlit (bootstrap card)
How to use if statment inside div tags with streamlit (bootstrap card)

Time:05-28

How to use if statement inside div tags with streamlit ? I am using bootstrap card with streamlit to display info from dataframe . What i need is to be able to display the content inside the bootstrap card when its not empty and hide the info when its empty .

code:

def card(ID,name,nickname,mother_name,bd):

    return f'''

    <div  style="width: 18rem;">

        <div >

            <h5 >ID: {ID}</h5>

            <h6 >Name: {name}</h6>

            <p >Nickname: {nickname}</p>

            <p >Date of Birth: {bd}</p>

            <p >Mother Name: {mother_name}</p>

        </div>

    </div>

    '''
st.markdown("""

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

""",unsafe_allow_html=True)

df_result_search = pd.DataFrame()
with st.sidebar.form(key='search_form',clear_on_submit= False):
     regular_search_term=st.text_input("Enter Search Term")
     if st.form_submit_button("search"):
         df_result_search = df[df['name'].str.contains(regular_search_term)|df['nickname'].str.contains(regular_search_term)|df['mother_name'].str.contains(regular_search_term)]
                        
                            
 st.write("{} Records ".format(str(df_result_search.shape[0])))
 for index ,row in df_result_search.iterrows():
         st.markdown(card(
                            row[0],
                            row[1],
                            row[2],
                            row[3],
                            row[4],
    ),unsafe_allow_html=True)

CodePudding user response:

We use style on display, if none we hide it. Results will be displayed for up to a max of 5 columns. Turn ON the wide mode if necessary.

Code

import math

import streamlit as st
import pandas as pd



data = {
    'ID': [1, 2, 3, 4, 5, 6, 7, 8, 9],
    'name': ['peter', 'john', 'james', 'james', 'james', 'james', 'james', 'james', 'james'],
    'nickname': ['pet', 'jon', None, 'james', 'jem', 'jack', 'jo', 'mes', 'ja'],
    'mother_name': ['maria', 'linda', 'ana', 'beth', 'vivian', 'rose', 'meg', 'sharon', 'neda'],
    'bd': ['2000-05-15', '2006-09-12', '2004-10-25', '1999-01-08', '2009-12-14', '2001-11-20', '1999-05-12', '2009-01-28', '2009-03-14']    
}

st.markdown("""
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" 
    integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
""",unsafe_allow_html=True)


def card(ID,name,nickname,mother_name,bd, v1, v2, v3, v4):
    return f'''
    <div  style="width: 18rem;">
        <div >
            <h5 >ID: {ID}</h5>
            <h6  style="display: {v1};">Name: {name}</h6>
            <p  style="display: {v2};">Nickname: {nickname}</p>
            <p  style="display: {v3};">Date of Birth: {bd}</p>
            <p  style="display: {v4};">Mother Name: {mother_name}</p>
        </div>
    </div>
    '''

df = pd.DataFrame(data)
st.write(df)

df_result_search = pd.DataFrame()
with st.sidebar.form(key='search_form',clear_on_submit= False):
     regular_search_term=st.text_input("Enter Search Term")
     if st.form_submit_button("search"):
         df_result_search = df[df['name'].str.contains(regular_search_term) |
                               df['nickname'].str.contains(regular_search_term) |
                               df['mother_name'].str.contains(regular_search_term)]
                        

rec = df_result_search.shape[0]
st.write("{} Records ".format(str(rec)))

num_rows = max(1, math.ceil(rec/5))

# Save cards data temporarily.
dv = 'inherit'
cards = []
for index, row in df_result_search.iterrows():
    v1 = dv if row[1] is not None else 'none'
    v2 = dv if row[2] is not None else 'none'
    v3 = dv if row[3] is not None else 'none'
    v4 = dv if row[4] is not None else 'none'
    cards.append([row[0], row[1], row[2], row[3], row[4], v1, v2, v3, v4])

# Show the card data.
if len(cards):
    for r in range(num_rows):
        num_cols = min(5, max(1, rec))
        c = st.columns(num_cols)
        for m in range(num_cols):
            if len(cards):
                mycard = cards.pop(0)
                c[m].markdown(card(*mycard), unsafe_allow_html=True)

Output

enter image description here

  • Related