Search code examples
jekyll

How can I address the header in an md-File using jekyll?


I am using Jekyll to generate my website. Currently I am building a navigation bar for the different subpages. Basically I have different md-files with multiple sections and each section starts with a headers such as for example:

##header 1
content
##header 2
content
...

I try to build a navbar, that directs you to the paragraph on my subpage that you are clicking on. (Such as the navigation in Wikipedia) The way, that I am currently using is to make one navigation.html for each subpage in my _includes folder. However, I am aware, that this might cause trouble, when the number of subpages increases.

What I want to do is basically:

{% for "header" in "each .md-file" %}
    <a href="#">{{ "name of header" }} </a>
{% endfor %}

I know for example, that in my _posts/post I could just do

{% for post in site.posts %}

However, I the md-Files I want to use are in my root-Directory and I do not know how to call them specifically.

To sum up: I have multiple .md-files in my directory and want to get each ##header as a link in a table of content.

Thanks in advance for any help!


Solution

  • As @marcanuy suggest, I would put your files in a _pages directory. Be sure to add include: ['_pages'] to your build settings in _config.yml

    Now you can go through the pages with {% for page in site.pages %} This still leaves the challenge of getting all the headers. When I was creating a specific type of TOC in jekyll, I found this piece of code very helpfull. You can use elements from there.

    A basic version of what you want would be the following. You'll have to tweak this based on your set-up, but it should do what you want. You could put this in a seperate html doc in _includes or place it directly in your navbar.

    
    {% for page in site.pages %}
    
    <ul>
        {% assign headers = page.content | split: '<h' %}
            {% for header in headers %}
                {% assign _string = header | split: '</h' %}
                {% capture _hAttrToStrip %}{{ _string[0] | split: '>' | first }}>{% endcapture %}
                {% assign title = _string[0] | replace: _hAttrToStrip, '' %}
    
                {% assign _idstring = header | split: 'id="' %}
                {% assign _idstring = _idstring[1] | split: '"' %}
                {% assign html_id = _idstring[0] %}
    
                <li>
                    <a href={{page.url}}#{{html_id}}>{{title}}</a>
                </li>
            {% endfor %}
    </ul>
    {% endfor %}
    

    Hope this helps!