How to properly style a markdown table

Introduction

While developing this my old blog using metalsmith in conjunction with metalsmith-markdown, I came across an issue, that didn't allow me to properly use markdown tables and style them accordingly.

Admittedly marked.js, which is used by the plugin, converted the following markdown...

| Tables        |      Are      |   Cool |
| ------------- | :-----------: | -----: |
| col 3 is      | right-aligned | \$1600 |
| col 2 is      |   centered    |   \$12 |
| zebra stripes |   are neat    |    \$1 |

...correctly into this:

<table>
  <thead>
    <tr>
      <th>Tables</th>
      <th align="center">Are</th>
      <th align="right">Cool</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>col 3 is</td>
      <td align="center">right-aligned</td>
      <td align="right">$1600</td>
    </tr>
    <tr>
      <td>col 2 is</td>
      <td align="center">centered</td>
      <td align="right">$12</td>
    </tr>
    <tr>
      <td>zebra stripes</td>
      <td align="center">are neat</td>
      <td align="right">$1</td>
    </tr>
  </tbody>
</table>

So far so good. But how on earth am I now able to apply the bootstrap table selectors to it?

Solution

The solution was to use a custom renderer and override the block level method for table.

var metalsmith = require("metalsmith")
var markdown = require("metalsmith-markdown")
var marked = require("marked")
var markedRenderer = new marked.Renderer()

markedRenderer.table = function(header, body) {
  const replaced_header = header.replace(/<th/g, '<th scope="col"')
  var table = `
        <table class="table table-striped table-dark">
            <thead>${replaced_header}</thead>
            <tbody>${body}</tbody>
        </table>
    `

  return table
}

metalsmith(__dirname)
  // ...
  .use(
    markdown({
      renderer: markedRenderer,
    })
  )
// ...

This allowed me to inject my custom classes and style it accordingly. Of course there are more block level methhods which you can override, have a look here: Marked.js Documentation