Convert markdown table of contents to HTML

Viewed 427

I am trying to convert a markdown document to HTML, using pandoc. I cannot get the HTML output to create the table of contents correctly.

Issue:

I have added a table of contents to the markdown doc, where clicking on each header takes the reader to the relevant section. I am using the format below, where clicking on 'Header Title' will send the reader to the section 'header' in the document:

[Header Title](#header)
  • I tried to convert this to HTML using the pandoc command
pandoc -i input.md -f markdown -t html -o input.html
  • This creates a valid HTML file I can open in Firefox, and the items in the table of contents show up as links - but when I click them, nothing happens (I am expecting it to jump to the relevant section)

  • This happens when I use either markdown or markdown_github as the input format (-i in pandoc)

Question:

  • How can I get the table of contents to show the expected behavior in HTML?

  • Or is the concept of 'table of contents' a wrong approach to HTML, and I should change my markdown code?

  • Apologies if I am going about this the wrong way, I have no experience with HTML / web documents.

I found a couple of similar questions but they seemed to be specific to other programming languages / tools, so any help how I can achieve this with markdown / pandoc is much appreciated.

I am using pandoc 1.19.2.4 on Ubuntu.

Example markdown:


- [Chapter 1](#chapter-1)
    - [1. Reading a text file](#1-reading-a-text-file)


## Chapter 1

This post focuses on standard text processing tasks such as reading files and processing text.

### 1. Reading a text file

Reading a file. 
1 Answers

Looking at your markdown file, you have used #1-reading-a-text-file as the id for the 1st subheading.

While converting it to HTML, the following line is generated for the subheading: <h3 id="reading-a-text-file">1. Reading a text file</h3>

The problem is the mismatch of "#1" which is present in the table of contents, but not in the heading. My guess is that pandoc does not allow HTML id to start with a number.

Changing the table of contents to the following should work:

- [Chapter 1](#chapter-1)
    - [1. Reading a text file](#reading-a-text-file)
Related