Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array from Symfony 2 controller to a TWIG template ?

Tags:

php

twig

symfony

I can`t pass an array from a symfony 2 controller to a TWIG template. I use this code in the controller:

$searchTerms['color'] = "Red";
return $this->render('TestBundle::search.html.twig', 
        array(
            "searchTerms" => $searchTerms));

In the twig template, I am trying to access the variable like this:

  1. {{ searchTerms['color'] }}
  2. {{ searchTerms.color }}

Both output nothing, empty string, so it seems like array comes to template but its elements are empty.

What`s wrong?

like image 819
sphinks Avatar asked Dec 11 '22 22:12

sphinks


1 Answers

Yes, this code works. The first thing to check is that your twig code is in the correct page (TestBundle::search.html.twig). This might sound silly but that happens sometimes...

If this is all good, I suggest that you try to debug within your template. Debugging is the most important thing. You will always have this kind of problem while programming, especially when you try something new. The better you are at debugging your code, the better you are as a programmer because there is no way you can get everything right the first time.

So, how can you debug?

To debug within your twig template, you can use the debug extension of twig. To activate the debug option, you will have to do a quick change in your config file. You can also read this thread if your lost.

You can debug any variable within your template like this:

<pre>
{% debug searchTerms %}
</pre>

This way, you can easily debug your variable and test what your problem is:

{% debug searchTerms['color'] %}

If you want to debug things quickly, I highly recommend that you use the LadyBugBundle. It is an awesome tool that will allow you to do something like that:

In your controller:

ladybug_dump($searchTerms);

In your TWIG template:

{{ searchTerms|ladybug_dump }}

Not that different from a classic var_dump option, but if you have long arrays or objects, ladybug will impress you. More importantly, in a controller, you will often have the need to stop the code at a certain point to avoid the page to load after your debug statement, this is fairly easy with ladybug:

ladybug_dump_die($searchTerms);

You can even ask ladybug to load the "debugged" variable into Symfony profiler with this simple statement.

$this->get('ladybug')->log($searchTerms);

You have now direct access of the variable from a tab of the Symfony2 profiler. Ladybug can do a lot more, but for this, the doc is really good.

like image 129
Mick Avatar answered Dec 14 '22 10:12

Mick