vanamp vanamp - 1 month ago 12
PHP Question

Using Twig to display PHP Object parameters

I am working on moving away from hard coded HTML in my PHP. I have had some success with basic Twig templates but am struggling with PHP objects. I have simplified things as much as possible and am still having issues displaying PHP Object parameters. Hopefully, I am just making a dumb mistake but I have spent a ton of time on this. If I remove my object and populate an array with data it works fine.

I am reading this in the twig documentation which makes me think it should work:

• check if foo is an array and bar a valid element;

• if not, and if foo is an object, check that bar is a valid property;

PHP:

<?php
require_once ('../vendor/twig/twig/lib/Twig/Autoloader.php');

Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem($_SERVER["DOCUMENT_ROOT"].'test/templates/');$twig = new Twig_Environment($loader, array(
'cache' => './tmp/cache',
));
$template = $twig->loadTemplate('test.phtml');

$obj = new Person();

$obj->fName = 'firstName';
$obj->lName = 'lastName';

$template->display(array($obj));


class Person{

public $fName;
public $lName;

}

?>


Template

<html>
<head><title>Twig template!</title></head>
<body>

Person
<ul>
{% for person in obj %}
<li>{{ person.fName }} {{ person.lName }}</li>
{% endfor %}
</ul>
</body>
</html>


If I do a var_dump I can see my object and the parameters are set. If I manuualy echo the parameters using

echo $obj->fName;


it returns the expected value. The template is showing up in the browser window correctly but the Twig portion is blank.

resulting HTML in browser:

<html>
<head><title>Twig template!</title></head>
<body>

Persons
<ul>
</ul>
</body>
</html>


any help is appreciated.

Answer

Try passing the obj array reference. Try this:

$template->display(array('obj' => array($obj)));

instead of this:

$template->display(array($obj));

Hope this help