Get Database Data Using Twig/Slim

Hello, I am Nils!

I have started to use Slim / Twig and whilst I’m a noobie, I’m loving it.

However, I need to show data from my database on the page. In traditional PHP obviously I would just use mysqli_query() and then return the results using a while loop, you get the point.

However, since you can’t write PHP in Twig (obviously) I don’t know how to render data from the database.

Does anybody know the trick? Cheers.

You should know that I am using Slim 2.6 and Twig 1.18. This is because I watched an out of date course, I’ll catch up to the latest version sooner or later.

Hi Nils,

I might go to Slim 3 (and possibly Twig 2) first and not bother with Slim 2, especially considering work is currently being done on Slim 4.

Can you show an example of how you are currently constructing the view? With Slim 3 (and Slims Twig-View component) you fetch the data you need from the database and pass it into the template to be rendered.

$data = 'foo'; // fetch data from the database here
return $this->view->render($response, 'data.html.twig', $data); // <-- pass $data to the template

Thank you so much for helping!

I see, so could the data variable be an associative array? And how would I use it in the Twig template?

If you were showing a user, for example.

$user = [
    'id' = 1,
    'name' => 'Nils'
];
return $this->view->render($response, 'user.html.twig', $user);
<a href="/user/{{ user.id }}">{{ user.name }}</a>

Which would render

<a href="/user/1">Nils</a>