According to https://learn.getgrav.org/17/advanced/flex/using/object#712b8c68bf0 we can get a single Flex Object from a Flex Collection by the key of the object:
{% set contact = grav.get('flex').object('gizwsvkyo5xtms2s', 'contacts') %}
However, I think in most cases we don't know the key and would like to get an object by the value of its property for example by a string in the title.
As to Flex Collection, we have the method search()
if we want to get modified collection by a string in property value and of course we can use this to get collection with one item.
But is there the same method to get a single Flex Object?
I see there is the method search()
for the Flex Object too. But as I can understand, it's just to determine whether a property contains a string or not only AFTER we have already got the object by its key.
Or if I'm wrong and we can get a single Flex Object by this search()
method, then how to do that in Twig template? Can you post an example?
So I need something like
{% set contact = grav.get('flex').object('contacts').search('Michael', ['first_name'], {'contains': true}) %}
I don't believe there is a function that returns an object by a given property:value.
Instead, you can use collection.filterBy({ 'first_name': 'michael' })
. https://learn.getgrav.org/17/advanced/flex/using/collection#filterby
If you're certain that michael
is going to be a value unique to that object and you just want to render it without looping through a collection, you can use Twig's |first
filter to access the first (only) object in the collection.
{% set contacts = grav.get('flex').collection('contacts') %}
{% set collection = contacts.filterBy({ 'first_name': 'michael'}) %}
{{ collection|first.first_name }}