[英]Accessing twig template variables from php
Is it possible to access every variable defined in a twig template from php? 是否可以从php访问twig模板中定义的每个变量?
Eg: 例如:
Template:
...
{% set foo = 'foo' %}
...
And from PHP: 从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'] = '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 of a letter 此代码打印: 一封信的主题
Variables you set in Twig are set into the $context
array you pass to Twig_Template->display()
. 您在Twig中设置的变量被设置到传递给
Twig_Template->display()
的$context
数组中。 This array is passed by value so any modifications to it will not be seen in the outer (PHP) scope. 此数组按值传递,因此在外部(PHP)范围内不会看到对它的任何修改。
So, no , you can't use the variables you set in Twig in PHP. 所以, 不 ,你不能使用你在PHP中的Twig中设置的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.