diff --git a/cheatsheets/jekyll/templating/table.md b/cheatsheets/jekyll/templating/table.md new file mode 100644 index 000000000..98ce027b0 --- /dev/null +++ b/cheatsheets/jekyll/templating/table.md @@ -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 + + + + + + + + + + + {% for author in authors %} + + + + + + + {% endfor %} + +
First NameLast NameAgeLocation
{{ author.first_name }}{{ person.last_name }}{{ author.age }}{{ author.location }}
+``` + +## 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 + + + + + + + + + + + {% for author in site.data.authors %} + + + + + + + {% endfor %} + +
First NameLast NameAgeLocation
{{ author['First name'] }}{{ author['First name'] }}{{ author['Age'] }}{{ author['Location'] }}
+``` + +### 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 %} + + + {% for row in rows %} + {% if forloop.first %} + + {% for pair in row %} + + {% endfor %} + + {% endif %} + + {% tablerow pair in row %} + {{ pair[1] }} + {% endtablerow %} + {% endfor %} +
{{ pair[0] }}
+``` + +{% endraw %}