Drupal 8 - Style Markdown table using Bootstrap theme

By xngo on January 12, 2020

In Drupal, when you use Markdown module and Bootstrap theme, a Markdown table is rendered as <table> without any class. In order for Bootstrap to recognize it as a table, a table class needs to be added in the table element, e.g. <table class="table">. There are multiple ways to do this. The simplest way that I found is to use JavaScript.

Use JavaScript to add the class

Edit .../themes/YOUR_THEME/YOUR_THEME.libraries.yml to add the followings:

    js/markdown.js: {}

It will tell Drupal to load js/markdown.js file.

In markdown.js, use JavaScript to add your desired Bootstrap class for the table. For my case, I prefer table table-striped classes.

(function ($, Drupal) {
  Drupal.behaviors.YOUR_THEME = {
    attach: function (context, settings) {
      // Add your Javascript code here.
      $('article div.content table').addClass('table table-striped');
})(jQuery, Drupal);

For the changes to take effect, log in your Drupal and navigate to Configuration > Performance. Then, clear your cache.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.