phpsymfonysymfony-2.6

How to return an array to twig in symfony2 and how to use it?


I have written an action in a controller. I want to pass "results" array to a twig file and also want to use it through for loop.

Here is my action code in controller

public function searchBookAction(Request $request)
{
       $q="PC";
       $conn = $this->get('database_connection');
       $results = $conn->fetchAll("SELECT name FROM products where name like '%".$q."%'");
    return array('results' => $results);
}

here is my twig code:

{%for data in results%}
<li>{{ data.name|e }}</li>
{% endfor %}
</ul>

In this code I get this error: Variable "results" does not exist in NimoProBundle:Product:product.html.twig


Solution

  • If you want to call to use searchBookAction from javascript (as you've ntioned in your comment), I would suggest you to take a look at JsonResponse. What it does is parsing the array into JsonFormat. The json can be decoded by javascript without problems.

    In your controller:

    public function searchBookAction(Request $request)
    {
        $q="PC";
        $conn = $this->get('database_connection');
        $results = $conn->fetchAll("SELECT name FROM products where name like '%".$q."%'");
        return new JsonResponse(array('results' => $results);
    }
    

    In your javascript code (I'm assuming you're using jQuery instead of writing the request by yourself):

    <script>
    $.get('path/to/your/controller', {}, function(response){
        response.results  //<- here you have your results
    });
    </script>