How to manually get the first element item in a JSON array that is already using a filter to format data as a date?

190 Views Asked by At

I'm trying to only retrieve the first instance in an array that contains multiple time slots inside of separate keys for a given real-world event (such as recurring weekly meetings).

This is how the twig code currently looks, resulting in a list of every single time slot:

 {% for event in data %}
  <img src="{{event.image}}">
   <h1>{{event.title}}</h1>
    <p>{% for t in event.timeslots %}{{t.start_date | date("D, M j @ g:i a") }} - 
{{t.end_date | date("D, M j @ g:i a") }}<br>
       {% endfor %}
      <a href="https://www.example.com/{{event.id}}"
target="_blank">See Details</a></p>
    <hr>
 {% endfor %}

This is what that looks like:

screenshot of multiple timeslots being displayed as found in the original twig code

But given that the timestamp is in unix format, I've already added a | date () filter, so I assumed adding a | first filter should work in filtering out all dates sans the first one in the array, as I've attempted here:

    {{t.start_date | date("D, M j @ g:i a") | first }}

But instead the resulting content that is displayed is the first letter of the first date repeated for the full count of the number of instances of the event.timeslots.start_date element.

Long story short, some of these events contain too many time slots to make practical sense in a design use case, so I essentially want to only cut it down to the start date of the first instance, and then display a text afterwards saying "+ ## more"

Here is an success scenario example of what I would like to accomplish:

screenshot of ideal output displaying only the first element of an array

1

There are 1 best solutions below

2
Fox Cadet On

Moving this over to answers because it was resolved via comments:

Looks like I needed to manually get the zero key from the array {{event.timeslots.0.start_date | date("D, M j @ g:i a") }} because using | first was merely repeating the first string for each key present in the array.

Further, I was also able to figure out how to display a dynamic text following the first date that informs of additional dates as a count and grammatically formats the plural/singular form of the word "time/s". See below:

{% for event in data %}
 <img src="{{event.image}}">
  <h1>{{event.title}}</h1>
   <p><strong>{{event.timeslots.0.start_date | date("D, M j @ g:ia") }}
{% if event.timeslots | length > 0 %} + {{event.timeslots | length}} 
more time{% if event.timeslots | length > 1 %}s{% endif %}{% endif %}</strong></p>
   <p><a href="https://www.example.com/{{event.id}}" target="_blank">
See Details</a></p>
  <hr>
 {% endfor %}