如何指定在Rmd报告中将toc扩展到哪个级别?

时间:2018-03-20 17:50:07

标签: r markdown r-markdown tableofcontents

生成Rmarkdown .html文档时,是否可以选择性地选择要显示的目录的默认部分?我有一个正在进行的Rmd报告,该报告定期更新,我希望以前的toc部分可用但折叠,只有最新的(或明确指出的部分)扩展。

---
title: "Main document"
date: "16 March 2018"
output: 
  html_document:
    mode: selfcontained
    toc: true
    toc_float: true
    toc_depth: 2
---

```{r child = 'document1.Rmd'}
```

```{r child = 'document2.Rmd'}
```

```{r child = 'document3.Rmd'}
```

1 个答案:

答案 0 :(得分:1)

您可以使用使用window.location property的微小JavaScript程序。

这是一个可重复的Rmd开头的第2.1小节:

---
title: "Document"
date: "16 March 2018"
output: 
  html_document:
    mode: selfcontained
    toc: true
    toc_float: true
    toc_depth: 2
---
# Section 1
## Subsection 1.1

## Subsection 1.2

# Section 2
## Subsection 2.1

## Subsection 2.2

```{js echo=FALSE}
window.location.href='#subsection_21';
```

为了使此示例适用于您的文档:

  1. 在浏览器中打开HTML文档,选择目标部分并阅读浏览器地址栏。地址以#section_title_or_something_like_that结尾。请注意这个id

  2. 将示例的js块复制到主Rmd文件的最后。更换
    #subsection_21与之前的id#section_title_or_something_like_that)。

  3. Knit您的主要文件!已经完成了。

  4. 如果您想避免主Rmd文件中的原始JavaScript,您还可以在script.html文件中包含这些行(不要忘记调整id):

    <script type="text/javascript">
    window.location.href='#subsection_21';
    </script>
    

    然后,使用以下命令在文档中包含此script.html文件:

    ---
    title: "Document"
    date: "16 March 2018"
    output: 
      html_document:
        mode: selfcontained
        toc: true
        toc_float: true
        toc_depth: 2
        includes:
          after_body: "script.html"
    ---
    # Section 1
    ## Subsection 1.1
    
    ## Subsection 1.2
    
    # Section 2
    ## Subsection 2.1
    
    ## Subsection 2.2