Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing twig template variables from php

Tags:

php

twig

Is it possible to access every variable defined in a twig template from php?

Eg:

Template:
...
{% set foo = 'foo' %}
...

And from PHP:

echo $template->foo

Or something like that.

like image 942
ZenMaster Avatar asked Oct 28 '11 17:10

ZenMaster


2 Answers

Accessing every variable is very cumbersome, so what I did in the end was to create an extension which holds the data that I need:

class SampleExtension extends Twig_Extension {
    private $foo;

    function getName() {
        return 'sampleExtension';
    }

    function getFunctions() {
        return array(
            'setFoo' => new Twig_Function_Method($this, 'setFoo')
        );
    }

    function setFoo($value) {
        $this->foo = $value;
    }

    function getFoo() {
        return $this->foo;
    }
}

And in the class where I needed the data:

$this->sampleExtension = new SampleExtension();
$twigEnv->addExtension($this->sampleExtension);
...
$html = $twigEnv->render('myTemplate.tpt', ...);

Using this template:

...
{{ setFoo('bar') }}
...

After render:

echo $this->sampleExtension->getFoo(); // Prints bar
like image 70
ZenMaster Avatar answered Sep 24 '22 03:09

ZenMaster


If you want to access template variable you can send this variable as reference.

$foo = '';
$args['foo'] = &$foo;
$twig->render($template, $args);
...
echo $foo;

Example: (the goal is to make email body and subject in one template)

Twig_Autoloader::register();
$loader = new Twig_Loader_String();
$twig = new Twig_Environment($loader);
$tl = <<<EOL
{% set subject = "Subject of a letter" %}
Hello, {{ user }}

This is a mail body

-- 
Site
EOL;
$mail['to'] = '[email protected]';
$mail['subject'] = '';
$args = array(
    'user' => 'John', 
    'subject' => &$mail['subject']
);
$mail['message'] = $twig->render($tl, $args);
print_r($mail['subject']);

This code prints: Subject of a letter

like image 30
tutankhamun Avatar answered Sep 24 '22 03:09

tutankhamun