Search code examples
arrayssymfonyvariablestwigtemplate-engine

Using three variables at same time to specify value in array with Twig


I have two arrays: teachers_number_array which contains the id of teachs and the another array 'teachers' witch contains the data of each teacher.

What I can't do is to show the name of a specific teacher based on its id:

{% for teachers_number in teachers_number_array %}
    {% if teachers_number in teachers|keys %}
        {{ teachers.teachers_number.name }} 
    {% endif %}
{% endfor %}

Solution

  • You can do something like this. Note that you can get the key of the array directly in the Twig loop (for id, teacher in teachers):

    PHP variables:

    $teachers_to_display = [2, 3];
    $teachers =  [
        1 => 'Fabien',
        2 => 'COil',
        3 => 'Tokeeen',
        'do not display' => 'Nooooo',
    ];
    

    Twig:

    {% for id, teacher in teachers %}
        {% if id in teachers_to_display %}
            {{ teacher }}
        {% endif %}
    {% endfor %}
    

    Will output:

    • COil
    • Tokeeen

    PS: If you have several properties just use teacher.name like you did before:

    $teachers =  [
        1 => [
            'name' => 'Pot',
            'firstname' => 'Fabien',
    ...