chrisjsewell / ipypublish
1 3
import string
2

3

4 3
class DefaultFormatter(string.Formatter):
5 3
    def get_value(self, key, args, kwargs):
6
        # Handle a key not found
7 0
        try:
8 0
            val = super(DefaultFormatter, self).get_value(key, args, kwargs)
9
            # Python 3, 'super().get_field(field_name, args, kwargs)' works
10 0
        except (IndexError, KeyError):
11 0
            if str(key).endswith("_pre"):
12 0
                val = "@ipubreplace{above}{" + str(key) + "}"
13
            else:
14 0
                val = "@ipubreplace{below}{" + str(key) + "}"
15 0
        return val
16

17

18 3
def convert_format_str(template):
19

20 3
    temp_str = "\n".join(template)
21 3
    fmt = DefaultFormatter()
22 3
    outstr = fmt.format(temp_str)
23

24 3
    return outstr
25

26

27 3
if __name__ == "__main__":
28

29 0
    template = [
30
        "{{%- extends 'null.tpl' -%}}",
31
        "{{% block header %}}",
32
        "{{{{ nb.metadata | meta2yaml('#~~ ') }}}}",
33
        "{{% endblock header %}}",
34
        "{{% block codecell %}}",
35
        "#%%",
36
        "{{{{ super() }}}}",
37
        "{{% endblock codecell %}}",
38
        "{{% block in_prompt %}}{{% endblock in_prompt %}}",
39
        "{{% block input %}}{{{{ cell.metadata | meta2yaml('#~~ ') }}}}",  # noqa: E501
40
        "{{{{ cell.source | ipython2python }}}}",
41
        "{{% endblock input %}}",
42
        "{{% block markdowncell scoped %}}#%% [markdown]",
43
        "{{{{ cell.metadata | meta2yaml('#~~ ') }}}}",
44
        "{{{{ cell.source | comment_lines }}}}",
45
        "{{% endblock markdowncell %}}",
46
    ]
47

48 0
    print(convert_format_str(template))

Read our documentation on viewing source code .

Loading