-
Notifications
You must be signed in to change notification settings - Fork 2
/
pre_pymarkdown.py
41 lines (35 loc) · 1.29 KB
/
pre_pymarkdown.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# -*- coding: utf-8 -*-
"""This preprocessor replaces Python code in markdowncell with the result
stored in cell metadata
"""
from nbconvert.preprocessors import *
import re
class PyMarkdownPreprocessor(Preprocessor):
def replace_variables(self, source, variables):
"""
Replace {{variablename}} with stored value
"""
try:
replaced = re.sub("{{(.*?)}}", lambda m: variables.get(m.group(1), ''), source)
except TypeError:
replaced = source
return replaced
def preprocess_cell(self, cell, resources, index):
"""
Preprocess cell
Parameters
----------
cell : NotebookNode cell
Notebook cell being processed
resources : dictionary
Additional resources used in the conversion process. Allows
preprocessors to pass variables into the Jinja engine.
cell_index : int
Index of the cell being processed (see base.py)
"""
if cell.cell_type == "markdown":
if hasattr(cell['metadata'], 'variables'):
variables = cell['metadata']['variables']
if len(variables) > 0:
cell.source = self.replace_variables(cell.source, variables)
return cell, resources