Make output cells like Markdown

2019-02-06 01:15发布

问题:

I like IPython's Markdown cells for incorporating HTML and other rich content inside notebooks. I would like to know if a command output can be formatted similarly, in output cells.

Here is one of my functions outputting HTML:

    print_html():
      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>
    """

The HTML code above, if placed in markdown (input) cell, produces nice link to the Matplotlib library. But in output cell it is just plain text. Any way to make it rich content?

回答1:

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.



回答2:

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>
"""


回答3:

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: