tags:

views:

35

answers:

2

Hi, I've a class that basically looks like this:

class App {
    public function newTemplate($filename, $vars=array())
    {
        $smarty = new Smarty;
        $smarty->compile_dir = $this->template_compile_path;
        if(count($vars) > 0)
        {
            foreach($vars as $v_key => $v_name)
            {
                $smarty->assign($v_key, $v_name);
            }
        }
        return $smarty;
    }
}

However, when I create a Instance of 'App', the reference to $smarty seems broken, as every call to the membermethods don't seem to do anything:

$app = new App;
$tpl = $app->newTemplate("index.tmpl");
$tpl->assign("foo", "bar"); // {$foo} does not appear with "bar" in the template

Now I wonder why? Of course I tried to use references:

...
public function &newTemplate()
...

... But that doesn't work. Variable references don't seem to work either:

...
$tpl = &$app->newTemplate("index.tmpl");
...

What is causing PHP here not to return a proper reference? Help is very appreciated!

+1  A: 

You're using $this->template_compile_path; to initialize Smarty. Have you initialized this? On a different note have you set PHP to display errors? Have you looked in your web server error log?

If you have a doubt about what a function returns use print_r on the result.

Manos Dilaverakis
Yes, $this->template_compile_path is defined inside the class. After playing around a little, I found the actual Problem (which I will post as answer)
nebukadnezzar
A: 

The solution doesn't seem very trivial, as Smarty doesn't allow changing variables once Smarty::display() has been called, which causes every call to Smarty::assign() to be lost.

So I created a overloaded class that inherits Smarty, and let it do the dirty job.

as conclusion:

  • never call Smarty::display() if you still have to assign vars in your template.
  • call Smarty::assign() before calling Smarty::display().

I found that behaviour a little strange myself, but whatever, I guess. :P

nebukadnezzar
On a somewhat unrelated note you might want to try to use PHP itself for templating one day. There was a time when I was an avid Smarty user until I stumbled on PHP frameworks that didn't use a third-party template system. These days I do it via PHP and I have to say it's made my life easier...
Manos Dilaverakis
I used to use PHP directly for templating too, but the lack of output-manipulating methods make it rather.. messy.
nebukadnezzar