0

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.

2
  • please check this url : smarty.net/docs/en/advanced.features.objects.tpl Commented Sep 26, 2014 at 14:18
  • @hardiksolanki I have already checked that link but I still can't find a way to assign the array of objects and access its elements from a template file. Commented Sep 26, 2014 at 14:27

3 Answers 3

1

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}
Sign up to request clarification or add additional context in comments.

Comments

0

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());

Comments

0

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

you can cast it to a string:

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

3 Comments

I tried this solution but whene I do {$objects} in the template file it prints Array
what is your expected output ?
No because I'm sure the array contains many objects and I want to access to their properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.