如何让Quarto Callout显示在网页TOC(目录)中
解决方案
要让Quarto网页中callout内的标题显示在TOC中,有两种可行方案:
方案1:使用Lua过滤器(编译时处理)
编写Lua过滤器,强制将callout内的标题标记为可纳入TOC的元素:
- 创建名为
toc-callouts.lua的文件,内容如下:
function Div(el) if el.classes:includes('callout') then for _, content in ipairs(el.content) do if content.t == 'Header' then content.attributes['toc'] = 'true' end end end return el end
- 在Quarto文档中引用该过滤器:
--- title: "some title" format: html filters: - toc-callouts.lua --- ## 1.1.0 Review ::: {.callout-caution appearance="simple" icon=false} ### Exercise 1.1.1 some code some text :::
编译文档后,callout内的标题会自动出现在TOC对应父章节的下方。
方案2:使用JavaScript(前端动态添加)
若不想用Lua过滤器,可通过页面加载后的JS代码,将callout内的标题手动插入TOC:
--- title: "some title" format: html --- ## 1.1.0 Review ::: {.callout-caution appearance="simple" icon=false} ### Exercise 1.1.1 some code some text ::: ```{js} document.addEventListener('DOMContentLoaded', function() { const calloutHeadings = document.querySelectorAll('.callout h3'); calloutHeadings.forEach(heading => { const headingText = heading.textContent.trim(); const headingId = heading.id; const parentSection = heading.closest('section'); if (!parentSection) return; const parentHeading = parentSection.querySelector('h2'); if (!parentHeading) return; const tocParentItem = document.querySelector(`#toc a[href="#${parentHeading.id}"]`).parentElement; const tocItem = document.createElement('li'); tocItem.classList.add('toc-item', 'toc-level-3'); const tocLink = document.createElement('a'); tocLink.href = `#${headingId}`; tocLink.textContent = headingText; tocItem.appendChild(tocLink); let tocSubList = tocParentItem.querySelector('ul'); if (!tocSubList) { tocSubList = document.createElement('ul'); tocSubList.classList.add('toc-child'); tocParentItem.appendChild(tocSubList); } tocSubList.appendChild(tocItem); }); });
该代码会在页面加载完成后,自动遍历所有callout内的h3标题,将它们添加到TOC中对应父章节的子列表里。
内容的提问来源于stack exchange,提问作者rutvik
相关产品推荐
相关产品推荐

