First, the code:
from random import choices
def random_name(length=6):
return "".join(choices("abcdefghijklmnopqrstuvwxyz", k=length))
# ---
from IPython.display import IFrame, display, HTML
import tempfile
from os import unlink
def display_html_to_frame(html, width=600, height=600):
name = f"temp_{random_name()}.html"
with open(name, "w") as f:
print(html, file=f)
display(IFrame(name, width, height), metadata=dict(isolated=True))
# unlink(name)
def display_html_inline(html):
display(HTML(html, metadata=dict(isolated=True)))
h="<html><b>Hello</b></html>"
display_html_to_iframe(h)
display_html_inline(h)
Some quick notes:
metadata=dict(isolated=True)
does not isolate the result in an IFrame, as older documentation suggests. It appears to prevent clear-fix
from resetting everything. The flag is no longer documented: I just found using it allowed certain display: grid
styles to correctly render.IFrame
solution writes to a temporary file. You could use a data uri as described here but it makes debugging your output difficult. The Jupyter IFrame
function does not take a data
or srcdoc
attribute.tempfile
module creations are not sharable to another process, hence the random_name()
.HTML('Hello, <b>world</b>')
at top level of cell and its return value will render. Within a function, use display(HTML(...))
as is done above. This also allows you to mix display
and print
calls freely.