Skip to content
● Grav 2.2 is out: 2x faster cold starts and 96% less memory on big sites. Read the announcement →

Help with array_unique function

Started by Simon Simfin 4 years ago · 4 replies · 628 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 FrViPofm, 4 weeks ago
4 481 3 weeks ago
Themes & Styling · by johan thomas, 5 years ago
1 806 3 weeks ago
Themes & Styling · by stuart young, 2 months ago
3 667 2 months ago
Themes & Styling · by Sebadamus, 3 months ago
5 686 2 months ago
Themes & Styling · by martynfoster735, 3 months ago
1 647 3 months ago