# 2.7 添加文章目录

根据文章的标题，显示文章的目录，这个应该也是比较基础的需求，所以Hexo在3.0版本中提供了辅助函数来实现这个功能，所以添加起来还是比较容易的。

## 1. 添加`toc.ejs`文件

在主题目录下`layout/_partial`文件夹中新建`toc.ejs`文件，存放文章目录的代码。

```markup
<% if (post.toc != false) { %>
<div id="toc">
  <%- toc(post.content, {list_number: false}) %>
</div>
<% } %>
```

这里的`toc()`函数就是Hexo官方提供的辅助函数，不用再自行写这部分代码了，直接调用`toc()`函数即可，`post.content`代表该文章内容，`list_number: false`是函数提供的一个配置参数，这里指定`false`代表文章列表不默认显示序号。

同时这段代码添加了一个文章变量`toc`，当在文章`front-matter`里添加`toc: false`时，就表示该文章不想显示目录。这样便可以控制哪些文章显示目录，哪些文章不想显示目录。

## 2. 添加到页面中

文章目录应该显示在文章内容的页面，这里将它放到文章的开始部分，找到主题目录文章布局文件`layout/_partial/article.ejs`，找到下面代码：

```markup
...
    <div class="article-entry" itemprop="articleBody">
      <% if (post.excerpt && index){ %>
        <%- post.excerpt %>
        <% if (theme.excerpt_link){ %>
          <p class="article-more-link">
            <a href="<%- url_for(post.path) %>#more"><%= theme.excerpt_link %></a>
          </p>
        <% } %>
      <% } else { %>
        <%- partial('toc') %>
        <%- post.content %>
      <% } %>
    </div>
...
```

可以看到，在`<%- post.content %>`前面添加了一行`<%- partial('toc') %>`引用了目录代码。现在刷新页面就可以看到目录了，如下图

![](https://2131732186-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LwGj1BtCBqfussZUC9t%2F-LwGm4SPlogRUsBnjO9e%2F-LwGmKzsv7lS_ZtUcqtK%2F2016-08-25-14-36-15.jpg?generation=1576551409207834\&alt=media)

## 3. 修改目录样式

上面也基本能满足文章目录的功能，只是不太好看，下面添加一些样式代码，让它看起来更美观一点。

在主题目录下`source/css/_partial`文件夹下找到`article.styl`文件，打开文件，在文件末端添加下面一段代码。

![](https://2131732186-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LwGj1BtCBqfussZUC9t%2F-LwGm4SPlogRUsBnjO9e%2F-LwGmKzuWWUnyIXInq1a%2F2016-08-25-14-41-32.jpg?generation=1576551409061612\&alt=media)

```css
...
#toc
  float right
  background-color #eee
  font-size 0.8em
  color color-link
  margin 5px
  .toc
    list-style none
```

重新刷新页面看看，如下图，看起来是不是美观了一些。

![](https://2131732186-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LwGj1BtCBqfussZUC9t%2F-LwGm4SPlogRUsBnjO9e%2F-LwGmKzwVtur6_nEn7uV%2F2016-08-25-14-44-00.jpg?generation=1576551409381127\&alt=media)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hexo.course.90byte.com/mu-lu/index-1/7.-tian-jia-wen-zhang-mu-lu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
