Skip to content

Commit

Permalink
Create table.md
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelCurrin authored Sep 10, 2024
1 parent 534b974 commit 31f9478
Showing 1 changed file with 147 additions and 0 deletions.
147 changes: 147 additions & 0 deletions cheatsheets/jekyll/templating/table.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
---
description: Convert data to a rendered table
---
# Table

I wrote this article which is on the tutorials section of the Jekyll docs covering this in detail - [Tabulate CSV Data](https://jekyllrb.com/tutorials/csv-to-table/).

See the short version below, for more data formats.

{% raw %}

## Render YAML data

As frontmatter on your page. Access using `page.authors`.

- `my-page.md`
```yaml
---
title: My page

authors:
- first_name: "John"
last_name: "Doe"
age: 35
location: "United States"

- first_name: "Jane"
last_name: "Doe"
age: 29
location: "France"

- first_name: "Jack"
last_name: "Hill"
age: 25
location: "Australia"
---
```

Access as `site.data.authors`.

- YAML file - `_data/authors.yaml`
```yaml
- first_name: "John"
last_name: "Doe"
age: 35
location: "United States"
- first_name: "Jane"
last_name: "Doe"
age: 29
location: "France"
- first_name: "Jack"
last_name: "Hill"
age: 25
location: "Australia"
```

Replace `author` with `page.authors` or `site.data.authors`.

```liquid
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Location</th>
</tr>
</thead>
<tbody>
{% for author in authors %}
<tr>
<td>{{ author.first_name }}</td>
<td>{{ person.last_name }}</td>
<td>{{ author.age }}</td>
<td>{{ author.location }}</td>
</tr>
{% endfor %}
</tbody>
</table>
```

## Render CSV data

Given CSV file:

- `_data/authors.csv`
```csv
First name,Last name,Age,Location
John,Doe,35,United States
Jane,Doe,29,France
Jack,Hill,25,Australia
```

### Hardcoded columns table

```liquid
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Location</th>
</tr>
</thead>
<tbody>
{% for author in site.data.authors %}
<tr>
<td>{{ author['First name'] }}</td>
<td>{{ author['First name'] }}</td>
<td>{{ author['Age'] }}</td>
<td>{{ author['Location'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
```

### Dynamic table

This approach is more flexible - it will work for any CSV and render all columns without having to reference them specifically.

Data is unpacked as a tuple of keys and values for each row, so we name this `pair` and slice it. Also note use of dynamic header - we read the column names for the first row.

```liquid
{% assign rows = site.data.authors %}
<table>
{% for row in rows %}
{% if forloop.first %}
<tr>
{% for pair in row %}
<th>{{ pair[0] }}</th>
{% endfor %}
</tr>
{% endif %}
{% tablerow pair in row %}
{{ pair[1] }}
{% endtablerow %}
{% endfor %}
</table>
```

{% endraw %}

0 comments on commit 31f9478

Please sign in to comment.