Search code examples
markdownjupyterbook

Referring to sub-section in a markdown file in another folder


Related to Markdown: Reference to section from another file

I have two markdown files:

├── parent.md
└── content/
    └── child.md

In parent.md:

# Main section
## sub-section

I'd like to make a reference to ##sub-section from child.md. How do I do that? Note that child.md is in a sub-folder.

Note that I am using Jupyter book to process the markdown.


Solution

  • Preface

    Generally, markdown processors will apply an ID to document headers so that one can create a hyperlink.

    Simply doing the following should work for most markdown processors:

    [parent sub-section](parent.md#sub-section)
    

    The downside to this approach is that when the header text changes, the ID changes, and therefore breaks the anchor link. Depending on the markdown processor you choose, there may be an idiosyncratic way to hardcode the anchor explicitly into the heading.

    Jupyter-book

    Since the processor you are using is Jupyter book, you can use section labels to cross-reference sections throughout your project.

    Example:

    Parent

    Markdown input:

    (parent:sub-section)=
    # sub-section
    

    Jupyterbook build output:

    <section id="sub-section">
    <span id="parent-sub-section"></span><h2>Sub-section<a class="headerlink" href="#sub-section" title="Permalink to this headline">#</a></h2>
    </section>
    

    Child

    Markdown input:

    [parent sub-section](parent:sub-section)
    {ref}`parent:sub-section`
    

    Jupyterbook build output:

    <p><a class="reference internal" href="../parent.html#parent-sub-section"><span class="std std-ref">parent sub-section</span></a></p>
    <p><a class="reference internal" href="../parent.html#parent-sub-section"><span class="std std-ref">Sub-section</span></a></p>
    

    Note: Depending on the size of your project, it may be worthwhile planning out how you would like to namespace your labels in advance.

    References