Search code examples
arraystwig

Get specific array element by matching key value in 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?


Solution

  • 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 %}