ZenMaster
ZenMaster

Reputation: 111

Accessing twig template variables from php

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.

Upvotes: 7

Views: 4213

Answers (3)

tutankhamun
tutankhamun

Reputation: 930

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

Upvotes: 1

ZenMaster
ZenMaster

Reputation: 111

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

Upvotes: 3

NikiC
NikiC

Reputation: 101946

Variables you set in Twig are set into the $context array you pass to Twig_Template->display(). This array is passed by value so any modifications to it will not be seen in the outer (PHP) scope.

So, no, you can't use the variables you set in Twig in PHP.

Upvotes: 0

Related Questions