Create index of definitions / theorems at end of bookdown book

后端 未结 2 868
忘了有多久
忘了有多久 2021-01-03 01:11

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

2条回答
  •  臣服心动
    2021-01-03 01:30

    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')
    ```
    

    Output:

    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 ...
    ```
    

提交回复
热议问题