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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With