繁体   English   中英

木材 Twig - 如果日期/时间是过去/现在/未来,则拆分类别帖子

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

我正在使用 ACF 链接到 Zoom 网络研讨会。 我使用 ACF 添加开始和结束日期/时间。 我有一个标准条件来检查这些字段上的过去/现在/未来

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

如何将存档帖子列表拆分为由过去/现在/未来条件定义的三个单独标题。

当前的网络研讨会


即将举行的网络研讨会


过去的网络研讨会


我目前没有将其他 arguments 传递到此页面。

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

-

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

我要创建 3 个单独的 for 循环吗? 我是否根据 if 条件进行排序?

任何帮助或指导在这里都会很棒。

我建议您在 PHP 模板中循环查看您的帖子,以便在上下文中将它们分开。 array_reduce function 可以帮助:

$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'  => [],
]);

然后在您的视图代码中,您可以使用一组非常简单的部分:

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

{# and so on for future & past #}

注意:我没有测试这段代码,但这是一般的想法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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