DiscoTOC - tabla de contenidos automática

:discourse2: Summary DiscoTOC will allow you to generate an interactive table of contents for your topics with one click!
:eyeglasses: Preview Preview on Discourse Theme Creator
:hammer_and_wrench: Repository Link https://github.com/discourse/DiscoTOC
:open_book: New to Discourse Themes? Beginner’s guide to using Discourse Themes

Install this theme component

Samples

Desktop

Mobile

Features

toc = table of contents

  • Automatically generates the entire toc via a button in the composer gear menu

  • The toc will always be on the screen - scrolls with content like the topic progress widget

  • As you scroll past sections in the topic, the active element in the table of contents will be set to active (blue highlight)

  • adds id attributes to headings (you can link to a specific section from another topic / post)

  • clicking on any link in the toc will instruct the browser to navigate to relevant section (smooth-scrolling)

  • adds a copy-able link next to each heading (if you want to link to it)

  • RTL support

  • The colors are based on your current active color palette

How does it work?

In a nutshell, it looks for headings in topics which are marked to have a toc (via the composer button) and if it turns out the current topic is marked, then it takes all the headings and puts them in the toc (nested in order of heading levels) - this means that your markdown must be syntactically correct.

# heading 1
## heading 2
### heading 3
#### heading 4
##### heading 5
###### heading 6

You’re free to go back and fourth in heading levels, but the order must be correct

# heading 2 
## heading 3
## heading 3
### heading 4
## heading 3
# heading 2

etc...

In order for the links in the toc to work, headings must have id attributes. The component will check if the headings already have ids and if they do, then they are respected. This is handy if you ever manually created a toc.

If the headings don’t have ids, then it will generate an id for each heading based on its text (unwanted characters are stripped out)

once all of that is done, it will also add a link next to each button that links directly to that section:

Settings

Name Description
minimum trust level to create TOC The minimum trust level a user must have in order to see the TOC button in the composer
composer toc text Text that appears at the top of the preview pane of the composer to indicate the topic will have a table of contents
auto TOC categories Automatically enable TOC on topics in these categories
auto TOC tags Automatically enable TOC on topics with these tags
TOC min heading Minimum number of headings in a topic for the table of contents to be shown

Translations

Translation Default
table_of_contents table of contents
insert_table_of_contents Insert table of contents
jump_bottom Jump to end
toggle_toc.show_timeline Timeline
toggle_toc.show_toc Contents

The theme comes with three strings that you can translate or change.

table_of_contents: "table of contents"

this used for the button that opens the toc on mobile

insert_table_of_contents: "Insert table of contents"

this is used as the text for the toc button in the composer gear menu

topic_will_contain_a_table_of_contents: "This topic will contain a table of contents"

This is the text that shows up in the composer preview to indicate that the a toc will be generated for the topic

How do I create a toc?

  1. Write a topic with syntactically correct headings
  2. Click the toc button in the gear menu (only shows up when creating a regular topic - replies and PMs are ignored
  3. Profit.

What happens to the topic progress widget when a topic has a toc?

As you can probably guess, there’s no space to show both at the same time, so the way this component works is as follows

in a topic with a toc, the topic progress widget is hidden while the first post is on screen, and you see the toc instead.

Once you scroll past the first post, the toc will not scroll with you and the topic progress will be shown instead while you read any replies.

So, first posts get the toc, and subsequent posts get the regular topic progress widget.

The happens on both desktop and mobile.

Are there any downsides to using this component?

Nothing I am aware of, all the changes are done on the client-side. So you can easily remove the component and your posts would go back to the way they were before you installed it.

Limitations

This component assumes the standard topic layout. As such, it won’t work with themes that modify that layout such as the Vincent theme. Support for popular themes that modify the layout will come at a later stage in the form of component settings.

Credit

I started with Greg Franko’s tocify.js library. However, it looks like it’s not been updated in a while, so this is essentially a hard-fork that removes a lot of unnecessary features, integrates and styles the rest for Discourse.

So, there are no external requests and the total size is ~ 4kb gzip.

Big thanks to @erlend_sh for lots of valuable feedback and to @david for his help with translations.

:discourse2: Hosted by us? Theme components are available to use on our Pro, Business and Enterprise plans.

Last edited by @tobiaseigen 2025-06-24T03:17:08Z

Check documentPerform check on document:
181 Me gusta

4 publicaciones se dividieron en un nuevo tema: ¿Cómo mover el TOC al lado izquierdo de la publicación?

No sé cómo se implementa este componente ni mucho sobre la estructura frontend de Discourse, así que solo puedo hacer una suposición.

¿No se podría mostrar la barra de progreso solo a) si hay más de 1 publicación en el tema y b) ajustar su inicio para que sea desde la segunda publicación (en lugar de la tercera), pero también c) añadir un margen inferior/superior cómodo a uno de los dos elementos para asegurarse de que el otro permanezca lo suficientemente alejado (por ejemplo, 1vh) como para no tener un aspecto extraño?

En otras palabras, en lugar de usar toda la segunda publicación como espacio, usar CSS para permitir algo de espacio entre ellos (si hay más de 1 publicación).

De nuevo, esto podría no tener ningún sentido ya que no sé mucho sobre cómo funciona esto en este momento.

3 Me gusta

¡Hola! Recientemente instalamos DiscoTOC para nuestros foros y nos preguntábamos si es posible hacer que el componente lea el texto alternativo (alt text) en las imágenes. Hemos usado imágenes para algunos encabezados de notas de parche…

así:
Rendimiento y Estabilidad

Y desafortunadamente, el sistema TOC no parece poder analizar una imagen como encabezado, creando una entrada en blanco en la lista y generando un enlace que te lleva a una página en blanco. ¿Hay alguna solución alternativa para esto aparte de “no usar imágenes”? ¡Gracias! Por lo demás, nos encanta el sistema.

1 me gusta

Mi suposición es que la solución es no usar imágenes como encabezados, pero es posible que haya una manera de lograr que funcione agregando algo de código a su sitio que se conecte con el código de DiscoTOC. Si vale la pena investigarlo o no, dependerá de cuán importante sea para usted usar imágenes en los encabezados de las publicaciones.

3 Me gusta

Hemos estado utilizando imágenes como encabezados en nuestras notas de parche de manera consistente durante bastante tiempo, y es parte de nuestra marca y presentación; no solo en los foros, sino también en Steam y otros lugares. Nos gustaría tener la capacidad de seguir utilizando imágenes como encabezados mientras usamos DiscoTOC para mantener la coherencia.

DiscoTOC ha sido excelente para otras cosas, como resúmenes de AMA, una megapublicación sobre nuestra aplicación de servidor dedicado, guías para nuevos jugadores, etc. Nos gusta mucho el sistema, pero nos encantaría tener un poco de funcionalidad adicional para la forma en que presentamos las notas de parche.

1 me gusta

La funcionalidad de anclaje de encabezado en este componente entra ligeramente en conflicto con la funcionalidad de Enlaces automáticos de encabezado añadida en 2.7.0beta6, ya que los encabezados obtienen dos iconos al pasar el ratón por encima, uno de Discourse y otro de DiscoTOC. ¿Hay alguna forma de evitar esto?

1 me gusta

Hola,

Puedes ocultar el ancla de Automatic header links con

.anchor {
  display: none;
}

Hola dodesz,

Hice el ancho de la publicación mucho más grande que el predeterminado, y después de instalar este componente se ve algo mal, ¿podrías decirme cómo solucionar este problema?

:heart: ¡gracias!

Selection_839

1 me gusta

En un foro que ejecuta Discourse 2.8.0.beta4 (90232af778), incluir el componente DiscoTOC provoca un mensaje de error:

oops

El componente se había activado antes y también había generado un problema con la versión de Discourse instalada anteriormente, aunque no puedo decir cuál era esa versión.

¿Puede encontrar algún mensaje de error relacionado con el problema en los registros de errores de su sitio?

Ese mensaje de error es un error de backend, mientras que DiscoTOC es un componente temático de frontend, por lo que es difícil que estén relacionados. ¿Tiene algún complemento instalado?

1 me gusta

Desafortunadamente, no pude encontrar nada útil en /logs.

Sí, aquí está el fragmento relevante de app.yml:

hooks:
  after_code:
    - exec:
        cd: $home/plugins
        cmd:
          - git clone https://github.com/discourse/docker_manager.git
          - git clone https://github.com/discourse/discourse-openid-connect.git
          - git clone https://github.com/discourse/discourse-checklist.git
          - git clone https://github.com/discourse/discourse-push-notifications.git
          - git clone https://github.com/discourse/discourse-characters-required.git
          - git clone https://github.com/angusmcleod/discourse-news.git
          - git clone https://github.com/discourse/discourse-data-explorer.git
          - git clone https://github.com/DNOeV/discourse-watch-category.git
          - git clone https://github.com/discourse/discourse-footnote.git
          - git clone https://github.com/discourse/discourse-knowledge-explorer.git
1 me gusta

Cuando un encabezado está dentro de una cita, el encabezado no aparece en la Tabla de Contenidos (TOC). ¿Se podría cambiar este comportamiento?

Este encabezado no aparecerá en la TOC

Contenido citado

Este encabezado SÍ aparece en la TOC

Contenido citado

No sé cómo está planeado que funcione, pero normalmente no, porque es parte de la cita, no un encabezado de ese texto.

1 me gusta

¿Podrías intentar usar el <blockquote> de HTML en su lugar? Eso permitiría que el encabezado # estuviera al comienzo de una línea.

Ejemplo:

<blockquote>

### Encabezado de Ancla

</blockquote>

Encabezado de Ancla

No lo he probado en una Tabla de Contenidos (TOC), pero parece funcionar con los encabezados con ancla automática en una publicación normal.

¿Por qué quieres que los encabezados dentro de las comillas aparezcan en la tabla de contenido? ¿Cuál es tu caso de uso?

Gracias por la idea. Sin embargo, no me funcionó.

Aquí hay un ejemplo de cuándo uso citas para estructurar visualmente el contenido que comienza bajo Área de Problema: Edad

3 Me gusta

¿Por qué estás usando la cita de esa manera? Decir la fuente es suficiente. Además, gramaticalmente eso está mal, incluso en inglés.

¿Es esto un error o solo otro usuario, pero… ¿cómo debo cerrar la Tabla de Contenidos (TOC)? Estaba buscando instrucciones básicas sobre cómo un usuario final debe usar los mensajes privados y, por supuesto, fui a la documentación para nuevos usuarios y abrí la TOC para ver si había alguna información.

Estaba usando un iPad y DiscourseHub.

Obtuve esto:

kuva

La TOC está bien. Pero está superponiendo texto y no pude hacer que se ocultara de nuevo. Así que, ¿qué demonios hice mal, o no hice nada en absoluto? :pleading_face: