Arrow Functions in Twig

Craft Closure and Laravel Collections in Twig

How to use Laravel Collections and closures in Twig.

Using the same data that is includ­ed in the pre­vi­ous video, Andrew shows how to use Lar­avel Col­lec­tions and his Craft Clo­sure Twig extension.

We start off by using the contains() method to find a weapon in a sim­ple 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 func­tion doesn’t know the struc­ture of the data we’re pass­ing in. How­ev­er, Twig doesn’t sup­port using arrow func­tions out­side of the three fil­ters 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 %}

How­ev­er, if we require the Craft Clo­sure pack­age in our Craft project, we can use arrow func­tions in oth­er places. So, we have to use the Craft Clo­sure Twig exten­sion to make that avail­able 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: