Skip to content
● Meet Grav Guard: keep every Grav site you run secure and up to date, all from one place. Free for up to 3 sites. Read more →

Help with array_unique function

Started by Simon Simfin 4 years ago · 4 replies · 796 views
4 years ago

Hi. I'm a relative newbie putting together a simple theme for personal use.

I have a loop which gets all the years of pages:

TWIG
{% for page in pages.children.visible.order('date', 'desc') %}
    {% set year = page.date|date('Y') %}
{% endfor %}

but I'm not sure how to get just the unique years from this array. I'm sure I need to use the array_unique Twig function - but I'm not sure exactly how.

Could someone help me out please?

Thank you.

4 years ago

Thanks. I'd seen the array_unique entry in the docs - but I can't see how to use it.

Could anyone give me a simple example please?

Thank you.

4 years ago

Hi, @simfin, based on your example

TWIG
{% set years = [] %}
{% for page in pages.children.visible.order('date', 'desc') %}
    {% set years = years|merge([page.date|date('Y')])|array_unique %}
{% endfor %}
{# test #}
{% for year in years %}
    <h1>{{ year|e }}</h1>
{% endfor %}

you should probably explain what you're trying to achieve, and note that pages.children won't get all pages, but the top level pages.

Suggested topics

Topic Participants Replies Views Activity
Themes & Styling · by MarkP, 2 weeks ago
3 191 2 weeks ago
Themes & Styling · by TomW, 2 weeks ago
0 110 2 weeks ago
Themes & Styling · by themetman, 3 weeks ago
1 205 3 weeks ago
Themes & Styling · by AH, 1 month ago
1 323 3 weeks ago
Themes & Styling · by Bruno, 4 years ago
6 1522 3 weeks ago