How to get section name in an .rmd file?

Viewed 130

Is it possible to capture the name of a section as a variable?

I have an .rmd document where each section follows the same format e.g.,

# The Beginning


### What we know about The Beginning


### What we need to learn about The Beginning

...

and I'd like to write something more generalized like

# The Beginning


### What we know about `r section_name`


### What we need to learn about `r section_name`

Is there a way to capture the current section name?

1 Answers

If you name a chunk 'The Beginning' you can refer to it throughout the Rmd using knitr::all_labels(), e.g.

---
title: "Test"
author: "Jared_Mamrot"
date: "22/12/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
```

# The Beginning
```{r The Beginning}
summary(cars)
```

### What we know about `r knitr::all_labels()[2]`
```{r 3rd_chunk}
# Refer to the 'label' inside the chunk
knitr::all_labels()[2]
```

### What we need to learn about `r knitr::all_labels()[2]`
```{r 4th_chunk}
cars %>% 
  ggplot(aes(x = speed, y = dist)) +
  geom_point() +
  ggtitle(label = knitr::all_labels()[2]) +
  theme_bw()
```

When I knit the Rmd, knitr::all_labels()[2] is replaced with "The Beginning"

example_knitted.png

EDIT: After re-reading your question I realise that this is not a complete answer. Perhaps you could somehow adapt this function for printing a Table of Contents to grab the section header and use it in the knitted doc.

Related