Hawiak
Hawiak

Reputation: 553

Twig Can't access objects

I've a object that loads a template via twig, but I want the template to access the objects variables ass wel, i thought i could use a tag called this and set this to $this in the class.

I've tried things like:

public function render_view($path, $file, $vars){
    $this->loader = new Twig_Loader_Filesystem($path);
    $this->twig = new Twig_Environment($this->loader, array());
    if(!isset($vars['this'])){
       $vars['this'] = $this;
    }
    $template = $this->twig->loadTemplate($file);
    return $template->render($vars);
}

Also tried

public function render_view($path, $file, $vars){
        $this->loader = new Twig_Loader_Filesystem($path);
        $this->twig = new Twig_Environment($this->loader, array());
        $processwire_vars = array('user', 'pages', 'page', 'sanitizer', 'files', 'input', 'permissions', 'roles', 'templates', 'session', 'config', 'controller', 'wire');
        foreach($processwire_vars as $key => $pw_v){
            if(!isset($vars[$pw_v])){
                $this->twig->addGlobal($pw_v, $this->$pw_v);
            }
        }
        $this->twig->addGlobal('this', $this);
        $template = $this->twig->loadTemplate($file);
        return $template->render($vars);
    }

And on my template

{{ this.title }}
{% this.render_snippet() %}

But i get this error:
Fatal error: Exception: Unknown tag name "this" in "layout.php" at line 7 (in /xxx/xxx/public_html/site/modules/MvcModule/Twig/Parser.php line 182) #0

Upvotes: 0

Views: 503

Answers (2)

Hawiak
Hawiak

Reputation: 553

I've figured it out.

It had to be

{{ instead of {% for functions.

What a silly mistake. Thanks @mcuadros for your help and time! (I did find the answer because of your link)

Upvotes: 0

mcuadros
mcuadros

Reputation: 4144

Can you try using $this as a global variable to Twig

$twig = new Twig_Environment($loader);
$twig->addGlobal('this', $this);

Or linking the function directly:

$twig = new Twig_Environment($loader);
$twig->addFunction(
    'render_snippet', 
    new Twig_Function_Function($this, 'render_snippet')
);

http://twig.sensiolabs.org/doc/advanced.html#functions

Upvotes: 1

Related Questions