4
votes

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?

2
Both syntaxes work for me (I just copied and pasted your code into a project of mine). Can you post the whole code of your controller and template?Carlos Granados

2 Answers

10
votes

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.

3
votes

I think you must change template like this:

{% for item in searchTerms %}
    {{ item.color }}<br/>
{% endfor %}

See official documentation: Creating and using Templates->embedding-controllers