Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific array element by matching key value in Twig

Tags:

arrays

twig

I have an array of objects passed to Twig from PHP and I would like to print the value of a specific entry in the array that matches another value, i.e.:

{{ teams('id' == user.team_id).name }}

Here's what I'm doing currently - and this can't be right, there must be a simpler way:

{% for team in teams %}
  {% if team.id == user.team_id %}
    {{team.name}}
  {% endif %}
{% endfor %}

Any suggestions?

like image 858
nockieboy Avatar asked Sep 06 '25 20:09

nockieboy


1 Answers

I don't know how your Controller (using Symfony?) looks like, but if the User is an object, you can simply use {{ user.team.name }}.

If that's not possible, you can use this:

{{ teams[user.team_id].name }}

Documentation

In case your the array keys don't match the id, you can even shorten your template with filter:

{% for team in teams|filter(team => team.id == user.team_id) %}
    {{team.name}}
{% endfor %}
like image 166
Stephan Vierkant Avatar answered Sep 11 '25 02:09

Stephan Vierkant