Slim 4 and Unable to get data in an array to show up in Twig

Hi I am wondering if I am going nuts.
I am able to get a list of users from my MYSQL database but seem unable to show them in the Twig view. Am I missing something?

My route: $app->get(‘/loop’, ‘App\Controller\LoopController:loop’);

My Controller:

<?php

namespace App\Controller;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Views\Twig;
use Doctrine\DBAL\Connection;

class LoopController
{
   private Twig $twig;
   private Messages $flash;
   private Connection $connection;

   public function __construct(Twig $twig, Messages $flash, Connection $connection)
   {
       $this->twig = $twig;
       $this->flash = $flash;
       $this->connection = $connection;
   }

   public function loop(Request $request, Response $response, array $args): Response
   {
       $query = $this->connection->createQueryBuilder();

       $rows = $query
           ->select('id', 'username')
           ->from('users')
           ->executeQuery()
           ->fetchAllAssociative() ?: [];

       $users = $rows;
       //var_dump($users);  <<<<this brings back the array of users
       return $this->twig->render($response, 'loop.html.twig', $users);
       // <<<<<Array $users should be available to the view when the route is entered.
   }
}

The loop.html.twig view:

       {% include 'header.twig' %}
       <p>Welcome to my homepage. Thanks for visiting!</p>
       <h1>Users</h1>
       <ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
     </ul>
      {% include 'footer.twig' %}

To pass a variable to Twig, the array must contain such a key.

Example:

$query = $this->connection->createQueryBuilder();

$users = $query
    ->select('id', 'username')
    ->from('users')
    ->executeQuery()
    ->fetchAllAssociative() ?: [];

$viewData = [
    'users' => $users,
];

return $this->twig->render($response, 'loop.html.twig', $viewData);
2 Likes