Unsafe_allow_html in code block

Hello!
While trying to solve a problem I am having (How to keep whitespace formatting - #4 by Placido_Pellegriti) I realized that, at the moment, it is not possible to allow html inside a code block. Is this so? Is there any workaround to do this?
As you might have already read in the answer to my previous question, I have tried using three backticks to enable code formatting (because st.code does not have the html parameter), but this prints out tags as β€œ&lr;” and β€œ&gr;”, while I need them to be interpreted.
Thank you a lot.

Hi @Placido_Pellegriti! :wave:

If you’re trying to display HTML content inside a Streamlit app and want the HTML to be rendered rather than just displayed as text, here are some options:

  1. Use st.markdown with unsafe_allow_html=True:

    st.markdown("<p>Your HTML content here</p>", unsafe_allow_html=True)
    
  2. Custom HTML with CSS for Code Styling:

    html_code = """
    <pre style="background-color: #f6f8fa; padding: 10px; border-radius: 6px;">
    <code>Your HTML content here</code>
    </pre>
    """
    st.markdown(html_code, unsafe_allow_html=True)
    
  3. Use an iFrame:

    st.components.v1.html('<iframe srcdoc="<p>Your HTML content here</p>" style="width: 100%; height: 150px; border: none;"></iframe>')
    

Note that using unsafe_allow_html=True can expose your app to security risks.

I hope that helps!

Best,
Charly

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.