/home/codeblock-labels-markdown

# Code Block Labels in Markdown

Published on

In another post, we explored adding captions to Markdown. It is recommended that you read that post first in order to gather understanding about Markdown’s history and specifications.

## #Code Blocks Labels?

When writing Markdown, you may have come across situations in which it would be handy to add labels to your code blocks to give context.

For example, you may be discussing dropping code into certain files and what to have a label specifying where this block of code belongs, like in this DigitalOcean post. Or, you want the code language to be displayed in a label so readers can tell what it is, like in my post about the Vim thesaurus.

A code block label adds context to your code block so that readers understand where it goes, what it does, or a myriad of other things. Unfortunately, there is no native way of accomplishing this.

## #The Info String

The line with the opening code fence may optionally contain some text following the code fence; this is trimmed of leading and trailing whitespace and called the info string.

The first word of the info string is typically used to specify the language of the code sample, and rendered in the class attribute of the code tag. However, this spec does not mandate any particular treatment of the info string.

CommonMark specs

The info string immediately following the opening of a code block seems like the ideal place for such a label. CommonMark has discussed adding attribute syntax to the info string (among other Markdown elements) with a general syntax like this:

markdown

python {id="python-print" class="blue large" data-filename="test.py"}
import time

print(2 + 2)



Although this syntax has been discussed for years, it has not been implemented into CommonMark. Some Markdown implementations allow syntax similar to the above, but with slight variations, so no syntax is very portable.

## #Inline HTML

Sounding familiar? Once again, inline HTML comes to the rescue. A simple solution is to just create a label element above the code block, then style the label to your desire. For example:

markdown

<p class="codeblock-label">test.md</p>

markdown
My ![foo bar](/path/to/train.jpg "title" )



Renders to:

test.md

markdown

My ![foo bar](/path/to/train.jpg "title" )


In this way, we can specify code block labels with whatever content we want, be it a filename, language, or anything.

You may notice that most of the code blocks on this website have the language in them. I have written Javascript to do this automatically.

## Meet the Author

John Allbritten

Nashville, TN

I love learning new technologies, and I have a passion for open source. As I learn things, my notes turn into articles to share.