Jakub W
Jakub W

Reputation: 185

How show json data with database in symfony

I have a little problem, because I have to show json date with database in Symfony3.

My controller

/**
     * @Route("/api/rest", name="rest_api")
     * 
     * 
     * @Template
     */
public function indexAction(Request $Request) {

    $Repo = $this->getDoctrine()->getRepository('CommonUserBundle:Comment');
    $row = $Repo->findAll();


    $data = json_encode($row, true);

    return array(
        'comment' => $data
    );
}

And this is my layout in html.twig

{% for comments in comment %}
           {{ comments }}
{% endfor %}

But I don't know why nothing show. Help me please :)

Upvotes: 0

Views: 1969

Answers (3)

Jenne
Jenne

Reputation: 883

Ok using my deductive skills (as your question is a bit vague) I am going to make the opposite assumption as everyone else did and say use the JSON helper function (Since 3.2).

return $this->json($myThings);

If you are working in older versions you need to return a proper Response object with the headers and such.

Upvotes: 1

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35963

try this:

  {% for comments in comment %}
       {{ comment }}
  {% endfor %}

If it doesn't work try to change and you want to print an array

$data = json_encode($row, true);

to $data = json_decode(json_encode($row), true);

if you want to print the string try this inside your twig

{{ dump(comments) }}

instead of this

{% for comments in comment %}
       {{ comment }}
  {% endfor %}

Upvotes: 0

goto
goto

Reputation: 8164

json_encode return a string.

Twig

{{ dump(comments) }}

Upvotes: 0

Related Questions