我发誓我已经在谷歌上搜索了这个,并试图理解文档,但我就是不明白。我正在写一个小函数,我不能理解的是我如何访问从函数内部传入渲染的变量。
如果我有这个注册我的扩展并调用render:
$o = new SomeObject();
$twig->addExtension(new MyExtension());
$twig->render('example.html',array('obj'=>$o))
example.html就是{{ myfunc('foo') }}
我如何从MyExtension中的myfunc内部访问变量'obj':
class MyExtension extends 'Twig_Extension
{
public function getName()
{
return 'myextension';
}
public function getFunctions()
{
return array(
new 'Twig_SimpleFunction('myfunc', 'MyExtension::myfunc', array('needs_environment' => true))
);
}
public static function myfunc('Twig_Environment $env, $name)
{
//how to I get 'obj' from $twig->render in here?
}
}
你想在函数声明中使用'needs_context' => true
:
new 'Twig_SimpleFunction('myfunc', [$this, 'myfunc'], [
'needs_environment' => true,
'needs_context' => true,
])
你会得到,作为第一个(或第二个,如果needs_environment
也为真)参数,与当前上下文的数据数组。这将保存您的变量。
public function myfunc('Twig_Environment $env, $context, $name)
{
var_dump($context);
}