Search code examples
htmlquarto

Show abbreviated section name in TOC with Quarto


Using Quarto markdown, is it possible to show alternative text in TOC, e.g. an abbreviated header text?

What I'd like to have in toc is:

Table of contents

1 First topic

While the first header looks like this:

# Some very long header about the first topic

An HTML solution would be fine too.


Solution

  • It can be done using a little bit of javascript, but this solution will only work for html output format.

    So use the file abbrv_toc.html in include-after-body and Set the text you want to show in TOC in toc-text attribute within the curly bracket just after the section name.

    ---
    title: "TOC Abbreviation"
    format: html
    include-after-body: abbrv_toc.html
    number-sections: true
    toc: true
    ---
    
    ## Some very long header about the first topic {toc-text="First Topic"}
    
    Quarto enables you to weave together content and executable code
    into a finished document. To learn more about Quarto see
    <https://quarto.org>.
    
    ## Some very long header about the second topic {toc-text="Second Topic"}
    
    When you click the **Render** button a document will be generated
    that includes both content and the output of embedded code
    
    ## More Header
    
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    

    abbrv_toc.html

    <script>
      function abbrv_toc() {
        let toc = document.querySelectorAll('nav#TOC li>a');
        toc.forEach(e => {
          let id = e.id.substring(4);
          let sec = document.getElementById(id);
          let toc_text = sec.getAttribute('data-toc-text');
          if(toc_text != null) {
            let new_toc_text = e.querySelector('span').outerHTML + ' ' + toc_text;
            e.innerHTML = new_toc_text;
          }
        })
      };
    
      window.document.addEventListener("DOMContentLoaded", function (event) {
        abbrv_toc();
      });
    </script>
    

    Shortened TOC Text