Mastodon

How to use bootstrap tables in Hugo

Mar 20, 2022 by Kolappan N

If you are using Hugo with Bootstrap, you would have noticed that any tables generated from markdown by Hugo will not have any Bootstrap styles in them. This is because Bootstrap requires specific classes to be added to the HTML table tag which is not present in the HTML from Hugo.

There are two ways to add these CSS classes

  1. Use Hugo Shortcodes with markdown content
  2. Write tables in HTML files directly

We are going to looking into the shortcode option in this blog post. First we need to create a shortcode name bootstrap-table.

The first step we need to do is to render the inner markdown content as table. As mentioned in the bootstrap document for responsive tables, we will enclose the table within a div and add the class table-responsive to the div element.

At this point our shortcode will look like,

<!-- Getting params -->
{{ $htmlTable := .Inner | markdownify }}

<!-- Table HTML code -->
<div class="table-responsive">
{{ $htmlTable | safeHTML }}
</div>

Now we add inputs to the shortcode that can be passed from markdown. The first input will be be the classes that are to be added to the <table> tag. The class table should be passed mandatory with other classes to further customize the table. Bootstrap supports classes like table-hover, table-bordered, table-striped, etc… to customize a table.

The second input for our shortcode will be classes for the table header. You can set classes like table-dark, table-primary just for the header to differentiate it from the rest of the table.

In the shortcode we will replace the <table> and <thead> tags part of the generated html with the tags that includes the classes that are passed as inputs.

The final shortcode for this is as follows

<!-- Getting params -->
{{ $htmlTable := .Inner | markdownify }}
{{ $table_class := .Get "table_class" }}
{{ $thead_class := .Get "thead_class" }}

<!-- Adding table classes -->
{{ $old_table_tag := "<table>" }}
{{ $new_table_tag := printf "<table class=\"%s\">" $table_class }}
{{ $htmlTable = replace $htmlTable $old_table_tag $new_table_tag }}

<!-- Adding header classes -->
{{ $old_thead_tag := "<thead>" }}
{{ $new_thead_tag := printf "<thead class=\"%s\">" $thead_class }}
{{ $htmlTable = replace $htmlTable $old_thead_tag $new_thead_tag }}

<!-- Table HTML code -->
<div class="table-responsive">
{{ $htmlTable | safeHTML }}
</div>

The markdown code that calls the shortcode will be like

{{ <bootstrap-table table_class="table table-hover" thead_class="table-dark"> }}
| Col 1 | Col 2 | col 3 |
|-------|-------|-------|
| Cell1 | Cell2 | Cell3 |
| Cell1 | Cell2 | Cell3 |
{{ </bootstrap-table>}}