Access to string template variables from php

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

For instance:

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

And from PHP:

 echo $template->foo 

Or something like that.

+6
source share
3 answers

Access to each variable is very cumbersome, so in the end I had to create an extension that contains the data 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 need the data:

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

Using this template:

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

After rendering:

 echo $this->sampleExtension->getFoo(); // Prints bar 
+3
source

The variables set to Twig are set to the $context array, which you pass to Twig_Template->display() . This array is passed by value, so any modifications to it will not be displayed in the external (PHP) area.

So no , you cannot use the variables set in Twig in PHP.

0
source

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

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

Example: (the goal is to make the body and subject of the email a single 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'] = ' a@example.com '; $mail['subject'] = ''; $args = array( 'user' => 'John', 'subject' => &$mail['subject'] ); $mail['message'] = $twig->render($tl, $args); print_r($mail['subject']); 

This code prints: Subject

0
source

Source: https://habr.com/ru/post/900308/


All Articles