-
I have a collection of game result posts:
I loop through the collection and show them on a page. I also show game statistics (e.g., win percentage, winning streak, etc.) on that same page. What I have now is a new collection:
So I'm recreating the collection, which feels wrong. It seems like filter is the more appropriate tool, where I could pass my game post collection to a filter and have it return stats. But then I'd need a filter for each stat, like So what's the best way to calculate data on a collection? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Not sure I'm 100% understanding your setup, but you could create a single filter that takes any arbitrary collection as an argument and returns a "stats" object (which sounds easier than creating n filters; one per stat). eleventyConfig.addFilter("gameStats", function (collection = []) {
return collection.reduce((acc, game) => {
const { points } = game.data;
acc.winPercentage = points[0] + points[1];
acc.streak = acc.streak + 1;
return acc;
}, { streak: 0 });
}); Where I created some fake data with front matter like this: ---
title: Golden State Warriors at Utah Jazz
points:
- 88
- 85
winner: Golden State Warriors
---
<h1>{{ title }}</h1> So verrrry terrible stats calculations, but yeah... I also created a src/posts/games/games.11tydata.json which sets {
"tags": ["games"]
} Now I can just refer to And my very bad, no good src/index.liquid looks something like this: ---
title: Stats
---
=
{%- assign stats = collections.games | gameStats -%}
<h1>{{ title }}</h1>
<pre>{{ stats | json }}</pre>
<p>Win Streak: {{ stats.streak }}</p>
<p>Win Pct%: {{ stat.winPercentage }}</p> And the generated HTML looks like: <h1>Stats</h1>
<pre>{"streak":2,"winPercentage":173}</pre>
<p>Win Streak: 2</p>
<p>Win Pct%: 173</p> I think one benefit of this is if you have multiple different seasons of games, you could just add new |
Beta Was this translation helpful? Give feedback.
Not sure I'm 100% understanding your setup, but you could create a single filter that takes any arbitrary collection as an argument and returns a "stats" object (which sounds easier than creating n filters; one per stat).
Where I created some fake data with front matter like this:
So verrrr…