Home » Php » Laravel – print_r in twig view

Laravel – print_r in twig view

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have a “simple” question I would hope, and that is how can I print_r or at least see the contents of all defined variables in a twig file.

I have tried: {{ variable }} (where variable is an array set for the view

$viewData['variable'] = array('1','2','3');

in the controller.

I have also tried: {{ $variable }} That gives an error.

I would just want to know what is available from my array in the twig file.

Answers:

You could use the built in {{ dump() }} function. See the documentation.

If you use it without any value in the brackets it will dump all variables available.
For dumping only your array you would do it like this:

{{ dump(viewData) }}

With something like xdebug the output looks quite nice and is readable.

array (size=3)
  0 => string '1' (length=1)
  1 => string '2' (length=1)
  2 => string '3' (length=1)

Although the documentation says it’s not available by default it was added in twig 1.5 and should be ready to use by default.

Of course not the same as print_r but with xdebug enabled it outputs nice and readable var_dump information.

Questions:
Answers:

The dump function works but requires the debug option enabled in the environment. If you don’t have the ability to set this you can also just loop through the array:

<pre>
{% for key, item in variable %}
    * {{ key }} - {{ item }}
{% endfor %}
</pre>

Questions:
Answers:

I’m not sure about doing it in Twig but you can use Laravel’s dd helper to dump and die from within the controller.

dd($viewData['variable']);

Questions:
Answers:

In Laravel 5.4 in config-> twigbridge.php set environment to 'debug' => config('app.debug', true)
Now twigbridge debug is enabled on Laravel env