Get content from a view and return a JSON

Hi guys,

simple ( apparently ) problem; I’d like to get content from a view, and return a JSON with that content.


 $response = $this->render($response, 'content.ajax', [
 'contentList'    => $contentList,

return $response->withJson([
	'html' => $response->getBody()->__toString() , >>> horrible but works

Is there another more elegant way to do this?


Yes. you can use the fetch() function on twig instead which does not put it into the response object but rather gives you a string back.

1 Like

In my controllers, my actions always return strings, which could be the result of a rendered twig template,
or a json result, or… you name it.

can you show me an example? tks!

Found it! It was exactly what I was looking for!


1 Like

Still, I give you some weird example :wink:

     * Display the info
     * @return string
    public function info()
        $phpinfo = ob_get_clean();
        $phpinfo = str_replace('img {float: right; border: 0;}', '', $phpinfo);
        $phpinfo = str_replace('a:link {color: #009; text-decoration: none; background-color: #fff;}', '', $phpinfo);

        return $this->view->render($this->response, $this->templateDir . '/info.twig', ['phpinfo' => $phpinfo]);

My twig (the usefull part)

{% set title = 'Info' %}
{% extends common ~ 'layoutmain.twig' %}

{% block content %}
{{ phpinfo | raw }}
{% endblock %}