CSV to HTML Table shortcode

Hi, I share a ready for production CSV to HTML table shortcode.

1/ Place CSV file in assets/data directory (CSV uses semi-colon “;” as separator and first line as table header. You can change the code.)

2/ In markdown, call the shortcode:
{{< csv-to-table file="/data/deficit-g6pd.csv" title="Blablabla" >}}

It can take named parameters: id (HTML id), class (CSS class) and title (table caption and schema markup).

3/ Place the following shortcode in layouts/shortcodes/csv-to-table.html

<!-- CSV to Table djibe Hugo shortcode
  CSV must use ; separator to preserve sentences where , can occur
  Support arguments: id, class, title.
  If no id provided: datatable-csv class is added for automatic initialization
  Tech: table caption, table headers (th with scope attribute), schema.org
-->
{{ $id := "" }}
{{ $title := .Get "title" }}
{{ $initializeClass := "" }}
{{ $extraClass := .Get "class" }}
  {{ with .Get "id" }}
    {{ $id = . }}
  {{ else }}
  <!-- Generate a random id for the table (a11y purpose) -->
  {{ $id = delimit (shuffle (seq 1 9)) "" }}
  {{ $id = printf "t-%s" $id}}
  {{ $initializeClass = "datatable-csv" }}
  {{ end }}
{{ with $file := .Get "file" }}
  {{ with resources.Get $file }}
    {{ with . | transform.Unmarshal (dict "delimiter" ";") }}
<table class="table {{ if $initializeClass }}{{ printf "%s" $initializeClass }}{{ end }} {{ if $extraClass }}{{ printf "%s" $extraClass }}{{ end }}" id="{{ if $id }}{{ printf "%s" $id }}{{ end }}" itemscope itemtype="https://schema.org/Table">
{{ if $title }}<caption id="{{ printf "table-caption-%s" $id }}" itemprop="about"><b>Table.</b> {{ printf "%s" $title }}</caption>{{ end }}
<thead>
<tr>
{{ range index . 0 }}
<th scope="col">{{ . }}</th>
{{ end }}
</tr>
</thead>
<tbody>
{{ range after 1 . }}
<tr>
{{ range first 1 . }}
<th scope="row">{{ . }}</th>
{{ end }}
{{ range after 1 . }}
<td>{{ . }}</td>
{{ end }}
</tr>
{{ end }}
</tbody>
</table>
{{ end }}
{{ else }}
  {{ errorf "The %q shortcode was unable to find %s. See %s" $.Name $file $.Position }}
{{ end }}
{{ else }}
  {{ errorf "The %q shortcode requires a file argument, the path to the CSV file relative to the assets directory. See %s" .Name .Position }}
{{ end }}
6 Likes