Expand variables in Markdown ipython-notebook cells

Inside the markdown cell in ipython-notebook, I would like to be able to automatically expand variables. It can be done?

As an example, consider the following code

from IPython.core.display import HTML from markdown import markdown base_url = "http://qaru.site/" 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 creates an output cell with the correct links, everything is relative to base_url , like

Two categories in /qaru.site / ... ipython-notebook and matplotlib .

I would like to be able to directly enter markdowns in a cell, referring to a predefined variable. Is it possible?

+7
ipython-notebook
source share
2 answers

Although this is not yet possible with a real Markdown cell, you can easily create 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 multiple variables

 foo = 1 bar = 2 

Then call the magic whose arguments are the variables you want to take from the namespace.

 %%markdown foo bar Substitute _{foo}_ and *{bar}* 
+6
source share

As @Jakob explained in the comments, the easiest way to accompany this is to install the python-markdown IPython extension , as described in the wiki page .

Then you can access your variables in the markdown method by surrounding them with curly braces:

Python cell:

 x = 1000 

Cell Markdown:

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

The markdown cell is analyzed as:

 Insert variable contents here -> 1000. 
+5
source share

All Articles