Add Floating TOC in Blogdown

Motivation

Question: How to add a floating TOC in my blogdown post?

Answer: It is not straightforward. I try to follow the Mickael’s approach and this one, then do the experiment.

Potential Approach

Step 1

Create <root>/layouts/_default/single.html.

{{- define "main" -}}
{{ if .Params.toc }}
<div class="container-fluid docs">
    <div class="row flex-xl-nowrap">
      <div class="d-none d-xl-block col-xl-2 docs-toc">
        <ul class="nav toc-top">
          <li><a href="#" id="back_to_top" class="docs-toc-title">{{ i18n "on_this_page" }}</a></li>
        </ul>
        {{ .TableOfContents }}
      </div>
      <main class="col-12 col-md-0 col-xl-10 py-md-3 pl-md-5 docs-content" role="main">
{{ end }}
        <article class="article">
            {{ partial "page_header" . }}
            <div class="article-container">
              <div class="article-style">
                {{ .Content }}
              </div>
              {{ partial "page_footer" . }}
            </div>
        </article>
  {{ if .Params.toc }}
      </main>
    </div>
  </div>
  {{ end }}
{{- end -}}

Step 2.

DONT USE .Rmd , using .Rmarkdown instead.

截屏2022-06-30 12.26.58

Further discussion

Further discussion and issues is here (Add a Floating Table of Contents in Blogdown \\\\| R & MC).

More Application

Activate the TOC

In every post you make where you would like a Table of Contents, you will need to ensure that you add toc: true in your front matter.

We can also use this code \{\{% toc %\}\} to show the table of content anyway in the post. For example,

Table of Contents

For LaTeX

For the $\LaTeX$, we have to use the shortcode, and put the latex code inside, check here.

$$ \gamma_{n} = \frac{ \left | \left (\mathbf x_{n} - \mathbf x_{n-1} \right )^T \left [\nabla F (\mathbf x_{n}) - \nabla F (\mathbf x_{n-1}) \right ] \right |}{\left \|\nabla F(\mathbf{x}_{n}) - \nabla F(\mathbf{x}_{n-1}) \right \|^2} $$

Summary

  1. 需要floating TOC
    • Step1 + Step2 设置好

    • Use .Rmarkdown , set toc:true in the yaml of the post.

    • .Rmarkdown 默认生成markdown,如果需要$\LaTeX$代码的话,必须使用shortcode

      • {{< math >}} … {{< /math >}}

      • 给它们包起来,这个是wowchemy academic theme要求的

  2. 需要TOC,在最上方就可以
    • Use .Rmd

    • Add this into the yaml part of the post

      output:
        blogdown::html_page:
          toc: true
      
    • LaTeX code works fine, NO Need to use shortcode.

  3. 所以,如果不需要浮动的TOC的话,直接选.Rmd 就好了,最方便简单也不会出什么问题。如果选择了.Rmarkdown 的话,latex 需要shortcode,也可能出现其他的问题。
Chen Xing
Chen Xing
Founder & Data Scientist

Enjoy Life & Enjoy Work!

Related