简体   繁体   中英

Timber Twig - Split Category Posts if Date/Time is Past/Present/Future

I am using ACF to link to Zoom Webinars. Ive used ACF to add both Start and End Date/Times. I have a standard condition that checks for Past/Present/Future on the these fields

{% if w_start %}
    {% if current >= w_start and current <= w_end %}
        {#% present %#}
    {% elseif current > w_end %}
        {#% past %#}
    {% else %}
        {#% future %#}
    {% endif %}
{% endif %}

How do I split an archive post list into three separate headings defined by a past/present/future condition.

Current Webinars


Upcoming Webinars


Past Webinars


I am presently not passing other arguments to this page.

$context['post'] = Timber::get_posts();
return Timber::render('webinar-archive.twig', $context, false);

-

{% for webinar in post %}
    {#% Do Something %#}
{% endfor %}

Do I create 3 separate for loops? Do I sort based on the if condition?

Any help or direction would be great here.

I suggest you loop over your posts in the PHP template so that they're separated within the context. The array_reduce function can help:

$context['posts_by_time'] = array_reduce(Timber::get_posts(), function($byTime, $post) {
  $start = strtotime($post->w_start);
  $end   = strtotime($post->w_end);

  if (time() > $start && time() < $end) {
    $section = 'current';
  } elseif (time() > $end) {
    $section = 'past';
  } else {
    $section = 'future';
  }

  // add this post to the correct section
  $byTime[$section][] = $post;

  return $byTime;
}, [
  'past'    => [],
  'current' => [],
  'future'  => [],
]);

Then in your view code you have a nice simple array of sections to work with:

<h2>Current Webinars</h2>
{% for webinar in posts_by_time.current %}
  {# render each current post #}
{% endfor %}

{# and so on for future & past #}

NOTE: I didn't test this code but that's the general idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM