How to use Laravel Collections and closures in Twig.
Using the same data that is included in the previous video, Andrew shows how to use Laravel Collections and his Craft Closure Twig extension.
We start off by using the contains()
method to find a weapon in a simple array.
{% set collection = collect(["money", "weapon", "food"]) %}
{% set contains = collection.contains("weapon") %}
{% dd contains %}
We then try to do the same thing against the data set we have, but it doesn’t work.
{% set collection = collect(ryansGoBag) %}
{% set contains = collection.contains("weapon") %}
{% dd contains %}
This doesn’t work because the collect
function doesn’t know the structure of the data we’re passing in. However, Twig doesn’t support using arrow functions outside of the three filters we’ve already discussed.
This code will not work in Twig:
{% set collection = collect(ryansGoBag) %}
{% set contains = collection.contains(
(item, key) => item.type == "weapon"
) %}
{% dd contains %}
However, if we require the Craft Closure package in our Craft project, we can use arrow functions in other places. So, we have to use the Craft Closure Twig extension to make that available using the contains()
method on the collection:
{% set collection = collect(ryansGoBag) %}
{% set containsWeaponArrow = (item, key) => item.type == "weapon" %}
{% set contains = collection.contains(containsWeaponArrow) %}
{% dd contains %}
Arrow Functions in Twig is made up of the following videos: