7

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.

3 Answers 3

3

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
1

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

1
0

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.

3
  • This might work if the variables inside that array are references. Have not tested it, but never say never :)
    – hakre
    Oct 28, 2011 at 17:50
  • Would it be possible if I sent in the context array an object and set properties of that object with a custom twig function?
    – ZenMaster
    Oct 28, 2011 at 17:53
  • @ZenMaster Yes, that would be possible ;)
    – NikiC
    Oct 28, 2011 at 18:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.