Sasha-Li Sasha-Li - 3 months ago 26
Markdown Question

Collapsible header in Markdow to html

Our internal git-lab wiki works with Markdown. I made several summaries of articles and want to post them in our wiki, in such a way that if I click on the header, it should unfold and the text should become visible, basically like in this example

Does Markdown have this expand/collapse/fold function?

Answer

Short Answer: No, Markdown does not offer a feature like that directly, but with some work you might be able to build something that works.

For a feature like that to work you would need some CSS and/or JavaScript to control the animations, etc. While you might be able to get such a feature to work on any HTML, it is not particularly easy on Markdown output.

Ideally, each collapsible section would be wrapped in a div:

<div id="section1">
  <h1>Section 1</h1>
  <p>Section 1 content</p>
  <div id="section1-1">
    <h2>Section1-1</h2>
    <p>section 1-1 content</p>
  </div>
    <div id="section1-2">
    <h2>Section1-2</h2>
    <p>section 1-2 content</p>
  </div>
</div>

Then you can use some CSS/JavaScript to collapse the individual sections. However, Markdown does not have a concept of sections. Instead of the above, Markdown would give you this flat document:

<h1>Section 1</h1>
<p>Section 1 content</p>
<h2>Section1-1</h2>
<p>section 1-1 content</p>
<h2>Section1-2</h2>
<p>section 1-2 content</p>

A solution would require looping through the entire document, breaking it up into the various sections and wrapping each section in divs. You can find a couple examples of that as Extensions to the Python-Markdown Parser. However, with any information regarding the environment you are working in, It is a little more difficult to point you in the correct direction. Besides, Stackoverflow is not supposed to be a tool recommendation site. However, by observing how others have solved the problem (in the examples I pointed to) you should be able to work out a similar solution.

Once you get the sections properly wrapped, then a little JavaScript to fold/collapse the individual sections will take care of the rest. However, that is a separate issue which has been asked and answered many times here. See some of the "Related" questions listed on the sidebar for solutions to that part of the problem.

It is even possible that some JavaScript libraries exist which will take the plain HTML content, do the section wrapping and implement the fold/collapse feature all in one. However, such a library may be a little heavy and slow down your site, so proceed with cation.

Comments