在书本结尾处创建定义/定理的索引 [英] Create index of definitions / theorems at end of bookdown book

查看:71
本文介绍了在书本结尾处创建定义/定理的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了方便读者,我想在书本的结尾处以降价方式写上书本正文的简单列表或定义索引.即使用自定义代码块创建的代码,例如:

For reader convenience, I'd like to include, at the end of my bookdown book, written in markdown, a simple list or index of definitions from the body of the book. i.e. ones created using custom blocks, like this:

```{definition, bar, echo=T}
A bar is defined here as a foo-like thing.
```

(我需要定义,但其他人可能喜欢定理列表等.不知道是否可以用相同的方式覆盖图形和表格的列表?)

(My need is for definitions, but others might like lists of theorems, etc. Don't know if lists of figures and tables could be covered in the same way?)

感谢@yihui,我知道knitr::all_labels(engine == 'definition')是我的朋友.

Thanks to @yihui I know that knitr::all_labels(engine == 'definition') is my friend.

因此,我可以在本书结尾处的任何地方(通常在结尾处)执行此操作:

So I can do this anywhere in the end of the book, usually at the end:

```{r comment="",results="asis",echo=FALSE}
knitr::all_labels(engine == 'definition') %>% unlist %>% paste0("\n\n","\\@ref(def:",.,"): ",.,"\n\n",collapse="\n\n") %>% cat

```

打印以下内容:

1: bar

2: foobar

带有可点击的数字.没关系但是,如果在每个标签之后也可以打印出实际的定义,那不是很好吗? (块的内容在knitr :: all_labels(engine =='definition')中不可用)

With clickable numbers. Which is OK. But wouldn't it be nice if, after each label, the actual definition could be printed too? (The content of the blocks is not available in knitr::all_labels(engine == 'definition'))

推荐答案

以下是使用输出格式bookdown::html_document2的示例,它也适用于任何其他书籍输出格式:

Here is an example using the output format bookdown::html_document2, and it should also work for any other book output formats:

---
title: "Test Definitions"
output: bookdown::html_document2
---

```{r setup, include=FALSE}
def_list = list()
knitr::knit_hooks$set(engine = function(before, options) {
  if (before && options$engine == 'definition') {
    # collect definition terms from options$name
    def_list[[options$label]] <<- options$name
  }
  NULL
})
```

```{definition, d1, name='Foo'}
Foo is defined as ...
```

```{definition, d2, name='Bar'}
Bar is defined as ...
```

All definitions in this document:

```{r echo=FALSE, results='asis'}
def_list = unlist(def_list)
cat(sprintf('- \\@ref(def:%s) %s', names(def_list), def_list), sep = '\n')
```

输出:

基本思想是使用块挂钩收集定义标签和名称,并在最后打印它们.您不必使用块选项name.它可以是任意选项,例如term.选项name是特殊的,因为定义的名称将打印在输出中.如果您不喜欢,可以使用例如term:

The basic idea is to use a chunk hook to collect definition labels and names, and print them at the end. You do not have to use the chunk option name. It can be an arbitrary option, e.g., term. The option name is special because the name of the definition will be printed in the output. If you don't like that, you can use, for example, term:

```{definition, d2, term='Bar'}
Bar is defined as ...
```

这篇关于在书本结尾处创建定义/定理的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆