How to make a collapsible code block?

Hi,

I love the markdown and highlight.js support in Hugo!

One thing I 'm looking for is a way to make the code blocks collapsible. Sometimes you have a lot of code in there and you would just want to show the first few lines, with an ellipsis and a ‘more’ link.

There are plenty of examples out there that explain how to do it with CSS and JQuery (e.g. viralpatel). But I wonder what the right way is to override the default behavior in Hugo.

Any suggestions?

Thanks!

1 Like

I think you could accomplish this pretty easily by writing your own custom shortcode.

Would you recommend wrapping the existing shortcode or creating a new one all together?

Any chance you could point me at the default shortcode source? I’ve been digging around the Hugo source code, but no luck so far.

Thanks!

This is entirely based on your preference. You can nest shortcodes (see the same link I added above), but the built in shortcode requires Pygments as server-side rendering. See here for more information on syntax highlighting:

https://hugodocs.info/tools/syntax-highlighting/

Thanks!

I’ve solved it by creating a wrapper shortcode. It takes ``` code blocks as input. I’ll put a brief post together on how it works and post the link here.

1 Like

@JiriDJ, this does not look too complicated to implement, but if you’ve already implemented it, would you mind sharing your code?

@giocomai, you can find the implementation and source code here:

https://jiridj.be/post/how-to-keep-blog-posts-with-large-code-blocks-readable/

2 Likes

Great thanks!

Someday maybe <summary> and <details> can be used for this. Unfortunately it’s not supported by the browsers from Microsoft yet. I’ve been using it with Hugo and this polyfil for a while.

It even works here! Hello world! :)

Hi I just stumbled on this old thread while looking for a way to make collapsible code blocks. I had a problem with the github code until I figured out that in the JS file it was treating maxHeight as a number rather than a pixel value (i.e. 300 when it should be ‘300px’). Posted it on this issues page: needs "parseInt" function to work · Issue #1 · jiridj/hugo-collapsible-code · GitHub

Thanks for sharing your code!