Skip to content

Instantly share code, notes, and snippets.

@jeromecoupe
Last active November 2, 2020 18:10
Show Gist options
  • Save jeromecoupe/c958c1c6600d37cd7a4fe5cc630734a7 to your computer and use it in GitHub Desktop.
Save jeromecoupe/c958c1c6600d37cd7a4fe5cc630734a7 to your computer and use it in GitHub Desktop.
Probably not a good idea: normalize array of objects in Craft
{# variables #}
{% set allNews = [] %}
{% set today = "now"|date("Y-m-d") %}
{# create custom allNews array of objects #}
{% set news = craft.entries()
.section(["news"])
.with([
"newsImage"
])
.orderBy("postDate DESC")
.limit(8)
.all() %}
{% for item in news %}
{% set thumbSmall = item.newsImage[0].getUrl({ width: 600, height: 450 }) ?? null %}
{% set thumbMedium = item.newsImage[0].getUrl({ width: 800, height: 600 }) ?? null %}
{% set allNews = allNews|merge([{
thumbSmall: thumbSmall,
thumbMedium: thumbMedium,
title: item.commonTitle,
url: item.url,
displayDate: item.postDate|date("Y-m-d"),
sortDate: item.postDate|date("U"),
typeFormatted: "News",
cssClass: "c-news--news"
}]) %}
{% endfor %}
{% set events = craft.entries()
.section(["events"])
.with([
"eventsImage"
])
.orderBy("eventStartDate DESC")
.eventEndDate(['and', ">= #{today}"])
.limit(8)
.all() %}
{% for item in events %}
{% set thumbSmall = item.eventImage[0].getUrl({ width: 600, height: 450 }) ?? null %}
{% set thumbMedium = item.eventImage[0].getUrl({ width: 800, height: 600 }) ?? null %}
{% set allNews = allNews|merge([{
thumbSmall: thumbSmall,
thumbMedium: thumbMedium,
title: item.commonTitle,
url: item.url,
displayDate: item.eventStartDate|date("Y-m-d"),
sortDate: item.eventStartDate|date("U"),
typeFormatted: "Event",
cssClass: "c-news--event"
}]) %}
{% endfor %}
{% set videos = craft.entries()
.section(["videos"])
.with([
"videoImage"
])
.orderBy("postDate DESC")
.limit(8)
.all() %}
{% for item in videos %}
{% set thumbSmall = item.eventImage[0].getUrl({ width: 600, height: 450 }) ?? null %}
{% set thumbMedium = item.eventImage[0].getUrl({ width: 800, height: 600 }) ?? null %}
{% set allNews = allNews|merge([{
thumbSmall: thumbSmall,
thumbMedium: thumbMedium,
title: item.commonTitle,
url: item.url,
displayDate: item.postDate|date("Y-m-d"),
sortDate: item.postDate|date("U"),
typeFormatted: "Vidéo",
cssClass: "c-news--video"
}]) %}
{% endfor %}
{# sort and slice #}
{% set allNews = allNews|sort((a, b) => a.sortDate < b.sortDate) %}
{% set allNews = allNews|slice(0,8) %}
{# display (@TODO: replace by a component using custom objects) #}
{% for item in allNews %}
<p>{{ item.displayDate }} - {{ item.typeFormatted }} - {{ item.title }}</p>
{% endfor %}
@brettburwell
Copy link

Nice. That definitely tightens things up even more. Thanks for sharing @jeromecoupe!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment