Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand variables in Markdown cells of ipython-notebook

Inside a markdown cell in an ipython-notebook I'd like to be able to expand variables automatically. Can this be done?

As an example, consider the following code

from IPython.core.display import HTML
from markdown import markdown

base_url = "https://stackoverflow.com/"
markdown_string = "Two categories at [stackoverflow]({0}) are "\
                  "[ipython-notebook]({0}questions/tagged/ipython-notebook) and "\
                  "[matplotlib]({0}questions/tagged/matplotlib).".format(base_url)
HTML("<p>{}</p>".format(markdown(markdown_string)))

This produces the output cell with the links correct, all relative to base_url, as

Two categories at stackoverflow are ipython-notebook and matplotlib.

What I would like is to be able to directly type the markdown into the cell, referencing a pre-defined variable. Is this possible?

like image 767
Ian Avatar asked Jan 26 '14 13:01

Ian


2 Answers

Although it's not possible yet to do with a real Markdown cell, you can easily create a magic to get the same effect.

from __future__ import absolute_import
from IPython.core.getipython import get_ipython
from IPython.core.magic import (Magics, magics_class,  cell_magic)

@magics_class
class MarkdownMagics(Magics):

    @cell_magic
    def markdown(self, line, cell):
        from IPython.core.display import HTML
        from markdown import markdown

        vars = line.split()

        d = {}
        for k, v in self.shell.user_ns.items():
            if k in vars:
                d[k] = v

        return HTML("<p>{}</p>".format(markdown(cell.format(**d))))

get_ipython().register_magics(MarkdownMagics)

Set some Variables

foo = 1
bar = 2

Then call the magic, with arguments being the variables you want to take from the namespace.

%%markdown foo bar

Substitute _{foo}_ and *{bar}*
like image 188
Eric Busboom Avatar answered Nov 08 '22 10:11

Eric Busboom


As @Jakob answered in the comments, the easiest way to accompish this is to install the python-markdown IPython notebook extension, as described on the wiki page.

You can then access your variables in markdown by surrounding them with curly brackets:

Python cell:

x = 1000

Markdown cell:

Insert variable contents here -> {{x}}.

The markdown cell gets parsed as:

Insert variable contents here -> 1000.
like image 30
ostrokach Avatar answered Nov 08 '22 09:11

ostrokach