Faery Faery - 1 year ago 147
JSON Question

How do I pretty-print an array?

I have an array like this:

$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));


and I want to print it in a readble way like this:

Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)


I have to pass the array to a Twig template. I tried this, but I don't get the result I want. Can you please advise me what do change?

In controller:

$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
$b = json_encode($a);
$c = json_decode($b, true);

return $this->render('AcmeTestBundle:Home:data.html.twig', array('data' => $c));


In template:

{% extends '::base.html.twig' %}

{% block stylesheets %}

<link href="{{ asset('bundles/acmetest/css/test.css') }}" type="text/css" rel="stylesheet" />

{% endblock %}

{% block body %}

{{ data }}

{% endblock %}


(this is base.html.twig: )

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>{% block title %}Welcome!{% endblock %}</title>
{% block stylesheets %}{% endblock %}
<link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
</head>
<body>
{% block body %}{% endblock %}
{% block javascripts %}{% endblock %}
</body>
</html>

Answer Source

Try with the Twig Debug Extensions:

Twig 1.x

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

Twig 2.x

{{ dump(user, categories) }}

The debug/dump tags only work when the debug environment option is set to true.

https://twig.symfony.com/doc/2.x/functions/dump.html

Also, you can try this without the debug extension:

$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));

return $this->render('AcmeTestBundle:Home:data.html.twig', array('data' => var_export($a, true)));

Inside your template:

<pre>{{ data }}</pre>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download