此code example to generate a list of definitions对我有用,但仅适用于一个索引列表。每当我尝试添加另一个列表(例如,针对定理)时,只有安装垃圾中最后一个定义的列表起作用。
可能我没有正确使用knit_hooks$set()
:
---
title: "Create several lists"
output: bookdown::html_document2
---
```{r setup, include=FALSE}
def_list = list()
knitr::knit_hooks$set(engine = function(before, options, envir) {
if (before && options$engine == 'definition') {
# collect definition terms from options$name
def_list[[options$label]] <<- options$name
}
NULL
})
thm_list = list()
knitr::knit_hooks$set(engine = function(before, options) {
if (before && options$engine == 'theorem') {
# collect theorem terms from options$name
thm_list[[options$label]] <<- options$name
}
NULL
})
```
```{definition, d1, name='Foo: My first definition'}
Foo is defined as ...
```
```{theorem, t1, name='My first theorem'}
First theorem ...
```
```{definition, d2, name='Bar: My second definition'}
Bar is defined as ...
```
```{theorem, t2, name='My second theorem'}
Second theorem ...
```
---
**All definitions:**
```{r echo=FALSE, results='asis'}
def_list = unlist(def_list)
cat(sprintf('- \\@ref(def:%s) %s', names(def_list), def_list), sep = '\n')
```
**All theorems:**
```{r echo=FALSE, results='asis'}
thm_list = unlist(thm_list)
cat(sprintf('- \\@ref(thm:%s) %s', names(thm_list), thm_list), sep = '\n')
```
OUTPUT:
问题是您已重置钩子。因此,您应该将钩子once设置为处理两个列表,如下所示:
---
title: "Create several lists"
output: bookdown::html_document2
---
```{r setup, include=FALSE}
def_list = list()
thm_list = list()
knitr::knit_hooks$set(engine = function(before, options) {
if ( before ) {
if ( options$engine == "theorem" ) {
thm_list[[options$label]] <<- options$name
} else if ( options$engine == "definition" ) {
def_list[[options$label]] <<- options$name
}
}
NULL
})
```
```{definition, d1, name='Foo: My first definition'}
Foo is defined as ...
```
```{theorem, t1, name='My first theorem'}
First theorem ...
```
```{definition, d2, name='Bar: My second definition'}
Bar is defined as ...
```
```{theorem, t2, name='My second theorem'}
Second theorem ...
```
---
**All definitions:**
```{r echo=FALSE, results='asis'}
def_list = unlist(def_list)
cat(sprintf('- \\@ref(def:%s) %s', names(def_list), def_list), sep = '\n')
```
**All theorems:**
```{r echo=FALSE, results='asis'}
thm_list = unlist(thm_list)
cat(sprintf('- \\@ref(thm:%s) %s', names(thm_list), thm_list), sep = '\n')
```
然后您将获得所需的输出: