# Buggy code
def _gen_toctree(options, subsections, parent_suff):
    options = "\n".join([f":{key}: {val}" for key, val in options.items()])

    # Generate the TOC from our options/pages
    toctree_text_md = """
    ```{{toctree}}
    :hidden:
    :titlesonly:
    {options}

    {sections}
    ```
    """
    toctree_text_rst = """
    .. toctree::
        :hidden:
        :titlesonly:
        {options}

        {sections}

    """

    if parent_suff in [".ipynb", ".md"]:
        toctree_template = toctree_text_md
    elif parent_suff == ".rst":
        toctree_template = toctree_text_rst

    # Create the markdown directive for our toctree
    toctree = dedent(toctree_template).format(
        options=options, sections="\n".join(subsections)
    )
    return toctree


# Traceback (UnboundLocalError)
Running Sphinx v3.3.0
making output directory... done
myst v0.12.10: MdParserConfig(renderer='sphinx', commonmark_only=False, dmath_enable=True, dmath_allow_labels=True, dmath_allow_space=True, dmath_allow_digits=True, amsmath_enable=False, deflist_enable=False, update_mathjax=True, admonition_enable=False, figure_enable=False, disable_syntax=[], html_img_enable=False, url_schemes=['mailto', 'http', 'https'], heading_anchors=None)
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 2 source files that are out of date
updating environment: [new config] 2 added, 0 changed, 0 removed
reading sources... [ 50%] notebooks
Extension error:
Handler <function add_toctree at 0x7f7b29674790> for event 'source-read' threw an exception (exception: local variable 'toctree_template' referenced before assignment)
Traceback (most recent call last):
File "/opt/conda/lib/python3.8/site-packages/sphinx/events.py", line 110, in emit
results.append(listener.handler(self.app, *args))
File "/opt/conda/lib/python3.8/site-packages/jupyter_book/toc.py", line 140, in add_toctree
toctrees.append(_gen_toctree(toc_options, toc_sections, parent_suff))
File "/opt/conda/lib/python3.8/site-packages/jupyter_book/toc.py", line 224, in _gen_toctree
toctree = dedent(toctree_template).format(
UnboundLocalError: local variable 'toctree_template' referenced before assignment

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/opt/conda/lib/python3.8/site-packages/jupyter_book/sphinx.py", line 141, in build_sphinx
app.build(force_all, filenames)
File "/opt/conda/lib/python3.8/site-packages/sphinx/application.py", line 352, in build
self.builder.build_update()
File "/opt/conda/lib/python3.8/site-packages/sphinx/builders/__init__.py", line 297, in build_update
self.build(to_build,
File "/opt/conda/lib/python3.8/site-packages/sphinx/builders/__init__.py", line 311, in build
updated_docnames = set(self.read())
File "/opt/conda/lib/python3.8/site-packages/sphinx/builders/__init__.py", line 418, in read
self._read_serial(docnames)
File "/opt/conda/lib/python3.8/site-packages/sphinx/builders/__init__.py", line 439, in _read_serial
self.read_doc(docname)
File "/opt/conda/lib/python3.8/site-packages/sphinx/builders/__init__.py", line 479, in read_doc
doctree = read_doc(self.app, self.env, self.env.doc2path(docname))
File "/opt/conda/lib/python3.8/site-packages/sphinx/io.py", line 223, in read_doc
pub.publish()
File "/opt/conda/lib/python3.8/site-packages/docutils/core.py", line 216, in publish
self.document = self.reader.read(self.source, self.parser,
File "/opt/conda/lib/python3.8/site-packages/sphinx/io.py", line 127, in read
self.input = self.read_source(settings.env)
File "/opt/conda/lib/python3.8/site-packages/sphinx/io.py", line 137, in read_source
env.events.emit('source-read', env.docname, arg)
File "/opt/conda/lib/python3.8/site-packages/sphinx/events.py", line 117, in emit
raise ExtensionError(__("Handler %r for event %r threw an exception") %
sphinx.errors.ExtensionError: Handler <function add_toctree at 0x7f7b29674790> for event 'source-read' threw an exception (exception: local variable 'toctree_template' referenced before assignment)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/opt/conda/bin/jupyter-book", line 8, in <module>
sys.exit(main())
File "/opt/conda/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/opt/conda/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/opt/conda/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/opt/conda/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/opt/conda/lib/python3.8/site-packages/jupyter_book/commands/__init__.py", line 259, in build
builder_specific_actions(
File "/opt/conda/lib/python3.8/site-packages/jupyter_book/commands/__init__.py", line 500, in builder_specific_actions
raise RuntimeError(_message_box(msg, color="red", doprint=False)) from result
RuntimeError:
===============================================================================

There was an error in building your book. Look above for the cause.

===============================================================================

# Fixed code
def _gen_toctree(options, subsections, parent_suff):
    options = "\n".join([f":{key}: {val}" for key, val in options.items()])

    # Generate the TOC from our options/pages
    toctree_text_md = """
    ```{{toctree}}
    :hidden:
    :titlesonly:
    {options}

    {sections}
    ```
    """
    toctree_text_rst = """
    .. toctree::
        :hidden:
        :titlesonly:
        {options}

        {sections}

    """

    if parent_suff in [".ipynb", ".md"]:
        toctree_template = toctree_text_md
    elif parent_suff == ".rst":
        toctree_template = toctree_text_rst
    else:
        return ""

    # Create the markdown directive for our toctree
    toctree = dedent(toctree_template).format(
        options=options, sections="\n".join(subsections)
    )
    return toctree