Sometimes I need to generate a header from within a code block so it be part of a conditional statement/control flow.
When I add a header using display() and Markdown() from IPython.display, the header is generated in the document, but not included in the table of contents (TOC).
---
title: "Test"
toc: true
format: html
---
```{python}
from IPython.display import display, Markdown
```
```{python}
for i in range(3):
display(Markdown(f'''## Header {i}
Lorem ipsum dolor sit amet, in at in sed nibh. Neque dignissim
ad imperdiet urna urna. In id erat aliquam, dolor ut odio.
Congue at, non justo fermentum urna suscipit ad torquent posuere.'''))
```
I also tried modifying the example code from the Quarto documentation, which is as follows:
```{python}
#| echo: false
#| output: asis
print("# Heading 1\n")
print("## Heading 2\n")
```
In my example, it becomes:
```{python}
#| echo: false
#| output: asis
for i in range(3):
print("## Heading using print() \n")
display(Markdown('''
Lorem ipsum dolor sit amet, in at in sed nibh. Neque dignissim
ad imperdiet urna urna. In id erat aliquam, dolor ut odio.
Congue at, non justo fermentum urna suscipit ad torquent posuere.'''))
```
Using the chunk option, #| output: asis does cause the headers to be included in the TOC, which is good, but the headers are printed one after another and then all of the other text is printed. So it's out of order in the rendered document.
What worked for me was use parts of each attempt from the question:
Use the
#| output: asischunk optionUse
display(Markdown('\n## Your header name')Note: Adding the newline before the header is important if you are including multiple headers within code. Otherwise, it's possible any header after the first one will render as regular text and not be included in the table of contents, especially if a plot immediately precedes the next header.