how can I show templates in a better manner in the following code?
import streamlit as st
from src.utils.db import DataBaseManager
def main():
st.title("Email Templates 📝")
st.write("Create and manage your email templates.")
code
db_manager = DataBaseManager()
# Form to add a new template
st.subheader("Add a New Template")
with st.form("template_form", clear_on_submit=True):
title = st.text_input("Template Title")
subject = st.text_input("Subject")
body = st.text_area("Body")
submitted = st.form_submit_button("Add Template")
if submitted:
template_data = {
'title': title,
'subject': subject,
'body': body
}
db_manager.add_template(template_data)
st.success(f"Template '{title}' added successfully!")
# st.experimental_rerun()
# Display existing templates
st.subheader("Existing Templates")
templates = db_manager.list_templates()
if templates:
for template in templates:
with st.expander(template['title']):
st.markdown(f"Subject: {template['subject']}")
st.markdown(f"Body:\n{template['body']}")
if st.button('Delete Template', key=template['title']):
db_manager.delete_template(template['title'])
st.success(f"Template '{template['title']}' deleted successfully!")
st.rerun()
else:
st.info("No templates have been added.")
if name == "main":
main()
Assistant
To display the email templates in a better manner within your Streamlit app, you can enhance the layout and formatting to improve readability and usability. Here are some suggestions:
Use Columns to Organize Templates: Display templates in multiple columns to make better use of the screen space.
Improve Formatting with Markdown and Code Blocks: Use Markdown for headings and emphasis, and code blocks or quote blocks for the template body to preserve formatting.
Add Edit Functionality: Allow users to edit templates directly from the interface.
Include Copy to Clipboard Buttons: Provide an option for users to copy the template body to their clipboard.
Implement Search or Filter: If you have many templates, adding a search function can help users find templates quickly.
Use Custom Styling: Enhance the visual appeal using custom CSS or HTML within Streamlit.
Below is the revised code incorporating these ideas:
python
import streamlit as st
from src.utils.db import DataBaseManager
import base64
import random
import string
def main():
st.title("Email Templates 📝")
st.write("Create and manage your email templates.")
db_manager = DataBaseManager()
# Form to add a new template
st.subheader("Add a New Template")
with st.form("template_form", clear_on_submit=True):
title = st.text_input("Template Title")
subject = st.text_input("Subject")
body = st.text_area("Body")
submitted = st.form_submit_button("Add Template")
if submitted:
if not title or not subject or not body:
st.warning("Please fill in all fields.")
else:
template_data = {
'title': title,
'subject': subject,
'body': body
}
db_manager.add_template(template_data)
st.success(f"Template '{title}' added successfully!")
st.experimental_rerun() # Rerun to update the list after addition
# Display existing templates
st.subheader("Existing Templates")
templates = db_manager.list_templates()
if templates:
# Search Functionality
search_query = st.text_input("Search Templates")
if search_query:
templates = [t for t in templates if search_query.lower() in t['title'].lower() or search_query.lower() in t['subject'].lower()]
if not templates:
st.info("No templates match your search.")
return
# Organize templates in columns
cols = st.columns(2) # Adjust the number of columns as needed
for idx, template in enumerate(templates):
col = cols[idx % 2]
with col:
display_template(db_manager, template)
else:
st.info("No templates have been added.")
def display_template(db_manager, template):
st.markdown(f"### {template['title']}")
st.markdown(f"**Subject:** {template['subject']}")
st.markdown("**Body:**")
st.code(template['body'], language='markdown') # Display body in a code block
action_col1, action_col2, action_col3 = st.columns([1,1,2])
with action_col1:
if st.button('✏️ Edit', key=f"edit_{template['title']}"):
edit_template(db_manager, template)
with action_col2:
if st.button('❌ Delete', key=f"delete_{template['title']}"):
db_manager.delete_template(template['title'])
st.success(f"Template '{template['title']}' deleted successfully!")
st.experimental_rerun()
with action_col3:
clipboard_button(template['body'], "📋 Copy Body")
def edit_template(db_manager, template):
st.subheader(f"Edit Template: {template['title']}")
with st.form(f"edit_form_{template['title']}"):
title = st.text_input("Template Title", value=template['title'])
subject = st.text_input("Subject", value=template['subject'])
body = st.text_area("Body", value=template['body'])
submitted = st.form_submit_button("Save Changes")
if submitted:
if not title or not subject or not body:
st.warning("Please fill in all fields.")
else:
updated_template = {
'title': title,
'subject': subject,
'body': body
}
db_manager.update_template(template['title'], updated_template)
st.success(f"Template '{template['title']}' updated successfully!")
st.experimental_rerun()
def clipboard_button(text, button_text="Copy to Clipboard"):
import streamlit.components.v1 as components
button_id = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
custom_css = f"""
<style>
#{button_id} {{
display: inline-flex;
align-items: center;
justify-content: center;
background-color: #f0f0f0;
color: #000;
border: none;
padding: 4px 8px;
margin-top: 5px;
cursor: pointer;
border-radius: 4px;
font-size: 14px;
}}
#{button_id}:hover {{
background-color: #e0e0e0;
}}
</style>
"""
copy_code = f"""
<button id="{button_id}">{button_text}</button>
<script>
const el = document.getElementById("{button_id}");
el.addEventListener("click", function() {{
navigator.clipboard.writeText(`{text}`);
el.textContent = 'Copied!';
setTimeout(() => el.textContent = '{button_text}', 2000);
}});
</script>
"""
components.html(f"{custom_css}{copy_code}", height=45)
if __name__ == "__main__":
main()
Explanation of Enhancements:
Columns for Templates:
Used st.columns() to display templates side by side, making efficient use of horizontal space.
Adjust the number of columns (st.columns(2)) based on your preference.
Improved Formatting:
Titles and Subheadings: Used markdown headers (###) for template titles.
Bold Labels: Emphasized "Subject" and "Body" labels using **bold** markdown syntax.
Code Blocks for Body: Displayed the template body within a code block using st.code(). This preserves formatting and distinguishes the body text.
Icons on Buttons: Added icons (e.g., ✏️ for Edit, ❌ for Delete, 📋 for Copy) to make action buttons more intuitive.
Edit Functionality:
Added an Edit button that, when clicked, displays a form pre-filled with the template's current data.
On submission, updates the template in the database and refreshes the page.
Copy to Clipboard Feature:
Implemented a clipboard_button() function using st.components.v1.html() to include HTML and JavaScript.
This function creates a button that copies the template body to the user's clipboard when clicked.
Search Functionality:
Included a search bar at the top of the template list.
Filters templates based on whether the search query appears in the title or subject.
Updates the displayed templates dynamically as the user types.
Action Buttons Layout:
Placed the Edit, Delete, and Copy buttons in a row using columns for better visual alignment.
Form Validation:
Added checks to ensure that the title, subject, and body are not empty when adding or editing a template.
Provides user feedback if validation fails.
Page Refresh after Actions:
Used st.experimental_rerun() after adding, editing, or deleting a template to ensure the displayed list is updated.
Additional Tips:
Custom Styling: You can further customize the look and feel by adding more CSS styles within the HTML components or using Streamlit theming options.
Pagination for Templates: If you have a large number of templates, consider implementing pagination or limiting the number displayed per page.
Confirmation Dialog for Delete: Before deleting a template, you might want to ask for confirmation to prevent accidental deletions. Streamlit doesn't have built-in modals, but you can simulate this with a checkbox or a separate confirmation step.
python
if st.button('❌ Delete', key=f"delete_{template['title']}"):
confirm = st.checkbox(f"Are you sure you want to delete '{template['title']}'?", key=f"confirm_{template['title']}")
if confirm:
db_manager.delete_template(template['title'])
st.success(f"Template '{template['title']}' deleted successfully!")
st.experimental_rerun()
Handle Duplicate Titles: Consider enforcing unique titles for templates or handling duplicates appropriately in your database logic.
Markdown Preview: If your template body uses Markdown, you could render a preview using st.markdown().
Responsive Design: Keep in mind that users might access your app from devices with varying screen sizes. Test the layout on different screen widths to ensure a good user experience.
Conclusion
By implementing these enhancements, you'll provide users with a more interactive and user-friendly interface for managing email templates. The improved layout, added functionalities, and better formatting will make it easier for users to create, view, edit, and utilize the templates effectively.
Feel free to adjust the code snippets to fit your specific requirements and to expand upon these ideas for even more functionality.