Frank
Frank

Reputation: 2173

How to assign an array of objects within a smarty template file

I have an array of stdclass objects. How can I assign it to a smarty template?

I tried to do this:

$smarty->assign( 'objects', $x->getAllObjects() ); 

but the result is an error:

Catchable fatal error: Object of class Object could not be converted to string

Thanks

edit: I also tried:

$smarty->registerObject( 'objects', $x->getAllObjects() );

and in the template file I did:

{foreach from=$objects item=o}
  {$o}
{/foreach} 

but I get a notice:

Notice: Undefined index: objects

and I can't access the elements of objects array.

Upvotes: 0

Views: 3566

Answers (3)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

We don't know what is your $x and getAllObjects() method.

However the following code for assigning objects for Smarty works without a problem

PHP file:

class X
{

    private $_objects;

    public function __construct()
    {
        $a = new StdClass();
        $a->name = 'John';

        $b = new stdClass();
        $b->name = 'Tom';

        $this->_objects[] = $a;
        $this->_objects[] = $b;
    }

    public function getAllObjects()
    {
        return $this->_objects;
    }


}

$x = new X();

$smarty->assign('objects', $x->getAllObjects());

Smarty file:

{foreach from=$objects item=o}
    {$o->name}
{/foreach}

Upvotes: 1

munsifali
munsifali

Reputation: 1731

$x->getAllObjects() is probably returning an object.

you can cast it to a string:

$string = (string) $x->getAllObjects();

Upvotes: 0

Matthew A Thomas
Matthew A Thomas

Reputation: 914

This depends on your smarty version.

But looking at the error messager you may need to do the following

$smarty->register_object('objects', $x->getAllObjects());

Upvotes: 0

Related Questions