Make output cells like Markdown

早过忘川 提交于 2019-11-30 08:24:22

Found a solution here: http://mail.scipy.org/pipermail/ipython-user/2012-April/009838.html

Quoting the solution here for ref:

Brian Granger:

" Have the function return the raw HTML wrapped in an HTML object:

from IPython.core.display import HTML
...
...
def foo():
    raw_html = "<h1>Yah, rendered HTML</h1>"
    return HTML(raw_html)

"

Now calling foo() does give rich formatted html as I wanted.

A somehow more advanced solution was recently published in a blog post here:

http://guido.vonrudorff.de/ipython-notebook-code-output-as-markdown/

It creates and registers a new IPython magic %%asmarkdown. The output of each code cell which you prepend with this command will be rendered like pure markdown cells. Using the content of the original question, the following would behave as expected:

%%asmarkdown
print """
<h2>Matplotlib's chart gallery (Click a chart to see the code to create it)</h2><br>
<div align="center"> <iframe title="Matplotlib Gallery" width="950"
height="250" src="http://matplotlib.org/gallery.html#api" frameborder="0"
allowfullscreen></iframe></div>
"""

Just adding some extra feature to your code example

htmlContent = ''

def header(text):
    raw_html = '<h1>' + str(text) + '</h1>'
    return raw_html

def box(text):
    raw_html = '<div style="border:1px dotted black;padding:2em;">'+str(text)+'</div>'
    return raw_html

def addContent(raw_html):
    global htmlContent
    htmlContent += raw_html


# Example
addContent( header("This is a header") )
addContent( box("This is some text in a box") )

from IPython.core.display import HTML
HTML(htmlContent)

gives you this:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!