Rmarkdown:是否可以仅在标签集中显示当前标签的目录

Rmarkdown : is it possible to display the TOC of the current tab only in a tabset

标题说明了一切...

如果我有一个 R-markdown 结构如下的文档

# TITLE { .tabset }

## First tab : mammals

### rabbits

### dogs

### elephants

## Second tab : birds

### sparrows

### swallows

我希望目录在第一个选项卡处于活动状态时仅显示项目 "rabbits, dogs, elephants",而在第二个选项卡处于活动状态时仅显示 "sparrows, swallows"。

非常感谢

这可能不是最简单的解决方案,但它应该可行,即使您在不同的选项卡面板上具有相同名称的部分也是如此。它是为您的 MRE 量身定制的,因此可能需要根据您的实际应用进行调整。

我用Javascript实现了你想要的。只需在您的 rmarkdown 文档的开头添加代码。

我希望评论能够清楚地说明正在发生的事情。

<script type="text/javascript">
$(document).ready(function() {
  var $tocItems = $(".tocify-subheader li.tocify-item"); // selector for all TOC items
  var $tabs     = $("a[role=\"tab\"]");                  // selector for all tabs
  var $panels   = $("div[role=\"tabpanel\"]");           // selector for all tabpanels

  $tocItems.hide();  // hide all TOC items

  // get the tab name for each section header (e.g. mammals)
  // and assign it to its corresponding toc item
  $panels.find("div[data-unique]").each(function() {
    var key = $(this).attr("data-unique");
    var tab = $(this).closest("div[role=\"tabpanel\"]").attr("id");
    $tocItems.filter("[data-unique=\"" + key + "\"]").attr("tab", tab)
  })
  // now each toc item knows to which tab panel it is pointing

  // show the toc items that point to sections on the first panel
  $tocItems.filter(function() {
    return($(this).attr("tab") === $tabs.first().text());
  }).toggle();

  // assign an onclick event to the tabs..
  $tabs.on("click", function() {
    $tocItems.hide();  // ... hide all TOC items
    var key = $(this).text(); // ... get the name of the tab clicked
    $tocItems.filter(function() {  // ... filter for the toc items pointing to that tab
      return($(this).attr("tab") === key);
    }).toggle();  // ... and show them
  });  
});
</script>