Tabs by month

Code

December 26, 2021

If you want to avoid the clutter of listing all posts as one big list, you might consider grouping them in accordions by month for instance. But how would you be able to do that yourself? You can do that easily in Toolbox using the Timber Posts module!

{# let's add 2 variables to keep track of current accordion's year and month #}
{% set year = false %}
{% set month = false %}
{# check if posts|length > 0 , no need to display anything if empty #}
{% if posts|length %}
<ul uk-accordion>
{% for item in posts %}
{# when getting to first item, open accordion first #}
{{ 
    year == false
        ? _self.open_accordion( item.date( 'F Y ' ) )
}}
{#
    when new item month or date is not equal to the previous
    we are switching to a new accordion. Close previous
    and open a new one (using concatenation operator ~ 
#}
{{ 
    (
        year != item.date( 'Y' ) or
        month != item.date( 'F' )
    ) and
    year != false
        ?   _self.close_accordion()
                ~
            _self.open_accordion( item.date( 'F Y ' ) )
}}
{# render the content of the item. #}
{{ _self.content( item ) }}
{#
  store the year and month of this item,
  so we can use it to compare for the next
#}
{% set year = item.date( 'Y' ) %}
{% set month = item.date( 'F' ) %}
{% endfor %}
{# close the last accordion #}
{{ _self.close_accordion() }}
</ul>
{% else %}
<p>Sorry no posts where found.</p>
{% endif %}
{#

#}
{% macro open_accordion( title ) %}
<li>
    <a class="uk-accordion-title" href="#">{{ title }}</a>
    <div class="uk-accordion-content">
{% endmacro %}
{#

#}
{% macro content( item ) %}
<p><a href="{{ item.link }}">{{ item.title }}</a></p>
{% endmacro %}
{#

#}
{% macro close_accordion() %}
    </div>
</li>
{% endmacro %}
Expand

Beaverplugins

Web ninja with PHP/CSS/JS and Wordpress skills. Also stand-in server administrator, father of four kids and husband to a beautiful wife.
Always spends too much time figuring out ways to do simple things even quicker. So that you can benefit.