My use case is specifically for PrismJS
where it needs certain classes in code tag for some additional code highlighting features like line-numbers
to show line number, match-braces
to highlight matching braces and so on.
I am using HUGO
for my blog where in markdown
files I am able to show some highlighted code block using below syntax:
```js console.log('Hello World!'); ```
I searched a lot but couldn't find the right way to add class to code fences such as shown above so I am doing it like this:
```js line-numbers match-braces console.log('Hello World!'); ```
This does the trick, but what is the right way to add classes in markdown
when using code fences ?
what is the right way to add classes in
markdown
when using code fences?
Whichever hack happens to work with the implementation you are using.
First of all, fenced code blocks are only partially standardardized. They are not in the original rules. However, they were more recently added to the Commonmark spec, which only provides for a single class to designate a language. Outside of that, the spec states:
An info string can be provided after the opening code fence. Although this spec doesn’t mandate any particular treatment of the info string, the first word is typically used to specify the language of the code block. In HTML output, the language is normally indicated by adding a class to the code element consisting of
language-
followed by the language name.
One example in the spec shows multiple items being defined:
~~~~ ruby startline=3 $%@#$
However, in the output only the first word survives. Everything else is lost.
<pre><code class="language-ruby">
As mentioned above, fenced code blocks were a recent addition to the Commonmark spec. Most implementations already supported them to varying degrees prior to them being specified. Therefore, there is a lot of variety in how anything beyond the first word is handled. You would need to check the documentation for the specific implementation you are using.
As you tagged this with [hugo]
, I checked Hugo's documentation, which examples suggests that only a single word is supported for language identification. Hugo's documentation also states that they use Goldmark under the hood to do the Markdown parsing. Goldmark labels itself a "standards-compliant" Commonmark implementation, which suggests that it will behave as documented in the specification. However, it does support third party extensions. Someone could always create an extension which supported more features in a fenced code block's info string.
Outside of a third party extension, you will need to resort to hacks to trick the parser into seeing multiple classes as a single word.