Search code examples
markdownjekyllkramdown

Add class to table rows in Kramdown


In kramdown, it is generally easy to add a class to some bit of text. Here, for example, is a blockquote:

> This is a blockquote.
{:.example}

HTML output:

<blockquote class="example">This is a blockquote.</blockquote>

While this technique works in many places, it doesn't appear to work with tables. I want to set a class on a table row. I expect the following to do the trick:

...
|one|two|three|{:.example}
...

In other words, I expect the following partial output:

<tr class="example">
...
</tr>

What I actually get is this:

<tr>
  <td>one</td>
  <td>two</td>
  <td>three</td>
  <td>{:.example}</td>
</tr>

I realize that I could just write the table in HTML, but I'd prefer to have the readability benefit of kramdown. Is it possible to do what I want in kramdown? If not, is there a better solution than dropping to HTML?


Solution

  • This is not currently possible in kramdown: see issues #417 and #436. If you want to stay within pure kramdown, you have to use HTML.

    If you don't want to do that and are willing to do some minor postprocessing, you could use some regular expressions. For example, if you want to style only the second row in the table

    | foo   | bar   | baz  |
    | xyzzy | plugh | thud |
    

    then

    $ kramdown file.md | perl -pe 's{tr}{++$n == 2 ? "tr class=\"waldo\"" : $&}ge'
    

    or

    $ kramdown file.md | tr '\n' '^' | sed 's/<tr/<tr class="waldo"/2' | tr '^' '\n'
    

    both produce:

    <table>
      <tbody>
        <tr>
          <td>foo</td>
          <td>bar</td>
          <td>baz</td>
        </tr>
        <tr class="waldo">
          <td>xyzzy</td>
          <td>plugh</td>
          <td>thud</td>
        </tr>
      </tbody>
    </table>
    

    Change 2 to whichever number you like. It's a kludge, but I'm not aware of other solutions that both use kramdown and don't revert to HTML tables.