Customizing nbconvert

Under the hood, nbconvert uses Jinja templates to specify how the notebooks should be formatted. These templates can be fully customized, allowing you to use nbconvert to create notebooks in different formats with different styles as well.

Out of the box, nbconvert can be used to convert notebooks to plain Python files. For example, the following command converts the example.ipynb notebook to Python and prints out the result:

In [1]:
!jupyter nbconvert --to python 'example.ipynb' --stdout

# coding: utf-8

# # Example notebook

# ### Markdown cells
#
# This is an example notebook that can be converted with `nbconvert` to different formats. This is an example of a markdown cell.

# ### LaTeX Equations
#
# Here is an equation:
#
# $$
# y = \sin(x)
# $$

# ### Code cells

# In[1]:

print("This is a code cell that produces some output")


# ### Inline figures

# In[2]:

get_ipython().magic('matplotlib inline')

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
plt.plot(x, y)

[NbConvertApp] Converting notebook example.ipynb to python

From the code, you can see that non-code cells are also exported. As mentioned above, if you want to change this behavior, you can use a custom template. The custom template inherits from the Python template and overwrites the markdown blocks so that they are empty.

Below is an example of a custom template, which we write to a file called simplepython.tpl. This template removes markdown cells from the output, and also changes how the execution count numbers are formatted:

In [2]:
%%writefile simplepython.tpl

{% extends 'python.tpl'%}

## remove markdown cells
{% block markdowncell -%}
{% endblock markdowncell %}

## change the appearance of execution count
{% block in_prompt %}
# This was input cell with execution count: {{ cell.execution_count if cell.execution_count else ' ' }}
{%- endblock in_prompt %}
Overwriting simplepython.tpl

Using this template, we see that the resulting Python code does not contain anything that was previously in a markdown cell, and has special comments regarding the execution counts:

In [3]:
!jupyter nbconvert --to python 'example.ipynb' --stdout --template=simplepython.tpl


# coding: utf-8

# This was input cell with execution count: 1
print("This is a code cell that produces some output")


# This was input cell with execution count: 2
get_ipython().magic('matplotlib inline')

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
plt.plot(x, y)

[NbConvertApp] Converting notebook example.ipynb to python

Template structure

Nbconvert templates consist of a set of nested blocks. When defining a new template, you extend an existing template by overriding some of the blocks.

All the templates shipped in nbconvert have the basic structure described here, though some may define additional blocks.

In [4]:
from IPython.display import HTML, display
with open('template_structure.html') as f:
    display(HTML(f.read()))

A few gotchas

Jinja blocks use {% %} by default which does not play nicely with LaTeX, so those are replaced by ((* *)) in LaTeX templates.

Templates that use cell metadata

The notebook file format supports attaching arbitrary JSON metadata to each cell. Here, as an exercise, you will use the metadata to tag cells.

First you need to choose another notebook you want to convert to html, and tag some of the cells with metadata. You can refer to the file soln/celldiff.js as an example or follow the Javascript tutorial to figure out how do change cell metadata. Assuming you have a notebook with some of the cells tagged as 'Easy', 'Medium', 'Hard', or <None>, the notebook can be converted specially using a custom template. Design your template in the cells provided below.

Hint: if your tags are located at cell.metadata.example.difficulty, the following Python code would get the value of the tag:

cell['metadata'].get('example', {}).get('difficulty', '')

The following lines of code may be a helpful starting point:

In [5]:
%%writefile mytemplate.tpl

{% extends 'full.tpl'%}
{% block any_cell %}
    <div style="border:thin solid red">
        {{ super() }}
    </div>
{% endblock any_cell %}
Overwriting mytemplate.tpl

Once you have tagged the cells appropriately and written your template using the cell above, try converting your notebook using the following command:

jupyter nbconvert --to html <your notebook.ipynb> --template=mytemplate.tpl