webGuy
webGuy

Reputation: 163

Forwarding a php array to twig template (Symfony)

I am trying to forward (render) my array from php to the twig template and than print everything out in the template. My problem is to access the array in the twig template.

Php array and render function:

    while ( $row = mysqli_fetch_array ( $queryResult ) )
    {
        $tplArray = array (
                array (
                        'id' => $row ['id'] 
                ),
                array (
                        'name' => $row ['name'] 
                ) 
        );

        $tplArray = array (
                'id' => $row ['id'],
                'name' => $row ['name'] 
        );
    }

    return $this->render ( 'work/work.html.twig', array (
            'data' => $tplArray 
    ) );

Trying to access the array in the twig template:

    {% for entry in data %}
        {{ entry.id }}
        {{ entry.name }}
    {% endfor %}

This obviously do not work. How can I get the data (id, name) from my $tplArray and print it out in the template?

Upvotes: 2

Views: 1057

Answers (1)

raina77ow
raina77ow

Reputation: 106375

Your while loop should look like this:

$tplArray = array(); 
while ( $row = mysqli_fetch_array ( $queryResult ) )
{
    $tplArray[] = array (
         'id' => $row ['id'],
         'name' => $row ['name'] 
    );
}

With this code, you assign an empty array (as a precaution) to $tplArray first. Then, using [] operator, you push a new element - an associative array with 'id' and 'name' attributes - at each step of while loop into this resulting array.

Currently, you reassign a new array as $tplArray value at each step of while instead.

Upvotes: 2

Related Questions