我试图将新功能添加到包含模板的Twig扩展文件中,并解析包含模板中的变量。而且我不知道如何从导入的模板获取变量。
我的模板
Config.html
{% set myVariable= "MyVariable" %}
template.html
{{layout("config") }}
My Config Variable: {{ myVariable }}
这是我的Twig扩展类。
class TwigExtensions extends \Twig_Extension {
public function getFunctions()
{
return array(
new \Twig_SimpleFunction(
'layout', array($this, 'twig_layout', ), [ 'needs_environment' => true, 'needs_context' => true, 'is_safe' => ['all'] ]
)
);
}
function twig_layout(\Twig_Environment &$env, &$context, $template, $variables = [], $withContext = true, $ignoreMissing = false, $sandboxed = false)
{
$file_name = (string)$template . ".html";
if ($withContext) {
$variables = array_merge($context, $variables);
}
$result = '';
try {
$result = $env->resolveTemplate($file_name)->render($variables);
// how to get variables from $file_name tempalte
} catch (Throwable $e) {
return "NULL"
}
return $result;
}
}