vanamp vanamp - 2 months ago 20
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;


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

$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';


class Person{

public $fName;
public $lName;




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

{% for person in obj %}
<li>{{ person.fName }} {{ person.lName }}</li>
{% endfor %}

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:

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


any help is appreciated.


Try passing the obj array reference. Try this:

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

instead of this:


Hope this help