Black Lives Matter. Please consider donating to Black Girls Code today.

Rendering HTML similar to Markdown

I have a tool in place that shows files from a specific directory in a data table. The user is able to click on those files and can show their contents in another div. I have this working for markdown files since there is a nice and easy component for rendering. However, the other file type is fairly complicated HTML (generated from converting word -> html). Would it be best to display this content in an iframe? If so, whats the best way to offer local files. Or, is it possible to use the HTML core components to display it?

For security reasons (XSS), it is not possible to render raw HTML. However, a current workaround is to display the HTML string inside the srcDoc attribute of an IFrame. Here’s an example:

import dash
import dash_html_components as html

app = dash.Dash()

app.layout = html.Div([
    html.Iframe(
        # enable all sandbox features
        # see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe
        # this prevents javascript from running inside the iframe
        # and other things security reasons
        sandbox='',
        srcDoc='''
            <h3>IFrame</h3>
            <script type="text/javascript">
                alert("This javascript will not be executed")
            </script>
        '''
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)
3 Likes

Awesome! That did the trick, thank you!

1 Like