Retrieve most recent event from HubDB

Hello everyone!

I’m trying to add a card to a webpage and that card info should come from an HubDB table.

I can see all the content on the page but I want only the nearest event and not the all list of future events. How can I limit the for loop so I have only one card?

Here is my actual code:

 {# query to sort chronologically #} 
 {% set queryparam = "&hide=0&orderBy=start_date" %} 

 {# the "today" variable gets the UNIX timestamp of the moment the page is loaded so we can determine if any webinar is in the future or in the past #} 
 {% set today = local_dt|unixtimestamp %} 

 {# loop trough table rows #} 
 {% for row in hubdb_table_rows(5591481, (queryparam)) %}

 {# format date #} 
 {% if row.end_date %}
 {% set date = row.start_date|datetimeformat('%B %e') ~ " –" ~ row.end_date|datetimeformat('%B %e, %Y') %} 
 {% else %} 
 {% set date = row.start_date|datetimeformat('%B %e, %Y') %} 
 {% endif %} 

 {# test to see if the event is in the future #}
 {% if row.start_date >= today || row.end_date >= today %}

 <div class="card mt-3 mt-sm-0 px-0 shadow border-0" style="width: 20rem;">
 <img src="{{ row.thumbnail.url }}">
 <div class="card-body">
 <div class="row justify-content-around">
 <div class="col-6">
 <p class="text-dark-blue mb-0">
 {{ row.type.name }}
 </p>
 </div>
 <div class="col-6">
 <p class="text-dark-blue mb-0 text-end">
 {{ row.start_date }}
 </p>
 </div>
 </div>
 <hr>
 <p class="fw-bold">{{ row.name }}</p>
 <p class="card-text">{{ row.description }}</p>
 <a href="{{ row.event_url }}" class="button btn-vg3">View more</a>
 </div>
 </div>
 {% endif %} {# ends date test #} 
 {% endfor %}

Thanks in advance!

@FilipaPF, happy Tuesday!

Thanks for reaching out to the HubSpot Community! :blush:

I’d like to tag some subject matter experts on this. @miljkovicmisa or @Indra, any chance you have any insights on this for @FilipaPF ?

Thanks!

Elyse

Meanwhile I solved the issue by adding: {% if loop.index <= 1 %} but I was wondering if there’s a better approach?

Thank you :blush:

The simplest way is to probably modify your initial query:

{% set today = local_dt|unixtimestamp %}
{% set queryparam = '&hide=0&orderBy=start_date&limit=1&start_date__gt=' + today %}

The query pulls only events after today, and then limits that output to only one. This will give you the closest upcoming event to right now. This would also make this if statement obsolete:

{% if row.start_date >= today || row.end_date >= today %}

… since the logic is handled in the query.