csv.html

The {{<csv>}} shortcode is a simple way to embed CSV files in your documentation from a global static/csv directory. This is great for large and/or complex tables that you want to keep separate from your markdown files.

Using this shortcode also enables you to more easily update your CSV files programmatically, without having to update the markdown files that reference them.

How it Works

The {{<csv>}} shortcode accepts 3 positional args: filename, delimiter, and excludedColumns.

  • filename is the name of the CSV file you want to embed. This file should be located in the static/csv directory. It does not need to include the .csv extension.
  • delimiter is the character that separates the columns in the CSV file. The default is ,.
  • excludedColumns is a comma-separated list of column numbers that you want to exclude from the table. The default is an empty string. This field is case-sensitive.

Examples

The table in the following examples is pulled from /static/csv/food.csv.

Full Table with Default Delimiter

{{<csv food>}}

Item Type Origin
Apple Fruit USA
Banana Fruit Ecuador
Carrot Vegetable Canada
Tomato Vegetable Italy
Bread Grain France
Cheese Dairy Switzerland

Full Table with Excluded Column

{{<csv food "," "Origin">}}

Item Type
Apple Fruit
Banana Fruit
Carrot Vegetable
Tomato Vegetable
Bread Grain
Cheese Dairy

Source Code

{{$filename := .Get 0}}
{{- $csv := printf "static/csv/%s.csv" $filename -}}
{{- $delimiter := .Get 1 | default "," -}}
{{- $skipColumns := split (.Get 2 | default "") "," -}} <!-- Get column names to skip as a list -->
{{- $data := getCSV $delimiter $csv -}}

<div class="overflow-x-auto">
    <table class="min-w-full divide-y divide-zinc-200">
        <thead class="">
            <tr>
            {{range $j, $col := index $data 0}} <!-- Loop through the first row to get headers -->
                {{if not (in $skipColumns $col)}} <!-- Check if column is not in skip list -->
                    <th scope="col" class="text-left uppercase tracking-wider">
                        {{$col}}
                    </th>
                {{end}}
            {{end}}
            </tr>
        </thead>
        <tbody class="divide-y divide-zinc-200">
            {{range $i, $row := $data}}
                {{if gt $i 0}} <!-- Skip the header row -->
                    <tr>
                    {{range $j, $col := $row}}
                        {{if not (in $skipColumns (index (index $data 0) $j))}} <!-- Use header row to check column name against skip list -->
                            <td class="whitespace-nowrap text-black">
                                {{$col}}
                            </td>
                        {{end}}
                    {{end}}
                    </tr>
                {{end}}
            {{end}}
        </tbody>
    </table>
</div>