Add TOC for markdown

  1. 1. TOC
  2. 2. doctoc
  3. 3. Hexo TOC
    1. 3.1. Theme layout
    2. 3.2. CSS file
  4. 4. Reference

TOC

This article introduce two ways that adding TOC for markdown files.


doctoc

Command line

1
2
npm install -g doctoc
doctoc .

It will add a TOC at the begining of your markdown files in all sub-folder.


Hexo TOC

Hexo will generate TOC automatically by modify two files as below.
Let’s take the default theme landscape for example.

Theme layout

file path:/themes/landscape/layout/_partial/article.ejs
Add the following code before line <%- post.content %>

1
2
3
4
5
6
<% if(post.toc !== false){ %>
<div id="toc" class="toc-article">
<strong class="toc-title">Table of contents</strong>
<%- toc(post.content) %>
</div>
<% } %>

CSS file

To avoid duplicateed prefixing indexs problem as below we need to disable the CSS list style.

1
2
1. 1. Level 1 Heading
2. 2. Level 1 Heading

file path:theme/landscape/source/css/_extend.styl
Change list-style: decimal to list-style: none

Reference

Github討論
给 Hexo 添加文章目录