我正在使用Symfony2组件更新一个遗留应用程序。我一直在尝试(而且大多失败)用小枝模板替换旧的php模板。
我正在挣扎的部分是:每个子模板都有自己的类,包含自己的逻辑(告诉过您这都是关于遗留的)。
因此,我创建了一个小枝扩展,它调用模板类,然后包含子模板,将类定义的变量(这是分机代码)传递给它。
例如:
{% template "NavBlockTemplate" %}NavBlockTemplate实例。getTemplateName以获取包含twig模板文件的getVariables以获取模板所需的varsTwig_Node_Include。
可悲的是:每个模板都可以将变量传递给它的子模板类构造函数.
所以,我需要的,但不确定它是否可能是这样的东西:
{% template "NavBlockTemplate" with { 'varName': value, 'var_id': otherVar.id } Twig_Expression对象到php vars的vars编译getTemplateName以获取包含twig模板文件的getVariables以获取模板所需的varsTwig_Node_Include。 那这有可能吗?关于如何做到这一点,有什么建议吗?
发布于 2015-09-18 16:12:13
在模板编译期间不能访问变量值。目前还没有。当您调用render($name, $context)时,小枝有两个不同的阶段
Twig_Environment::render()的实现很容易看出这两个步骤
public function render($name, array $context = array())
{
return $this->loadTemplate($name)->render($context);
}您的自定义标记需要说明这一点。它将需要创建一个特殊的节点类,该类将被编译成所需的逻辑。您可以查看现有Twig标记的实现方式。
甚至您所包含的类名也可以在编译时像您所做的那样被访问。只有当表达式是一个常量表达式,并且在解析器中不强制使用它时,$expr->getAttribute('value')才能工作。
另一方面,在这种情况下使用标记可能不是最好的解决方案(尽管它是最复杂的)。根据Twig的语义,函数会更好。这正是为什么Twig也引入了include()函数,因为它更适合。这就是它的样子。
在模板中:
{{ include_legacy("NavBlockTemplate", { 'varName': value, 'var_id': otherVar.id }) }}在延期部分:
class LegacyIncludeExtension extends \TwigExtension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction(
'include_legacy',
array($this, 'includeLegacy'),
array('is_safe' => array('all'), 'needs_environment' => true, 'needs_context' => true)
),
);
}
public function includeLegacy(\Twig_Environment $env, array $context, $name, array $variables = array())
{
$fqcn = // determine the class name
$instance = new fqcn();
$template = $instance->getTemplateName();
$variables = array_merge($instance->getVariables(), $variables);
return $env->resolveTemplate($template)->render(array_merge($context, $variables));
}
}该方法的最后一行执行twig_include的主要工作。如果您需要对隔离上下文的支持,这很容易(将模板的数组合并作为条件)。对ignore_missing的支持是更多的工作,在这种情况下直接调用twig_include会更好:
public function includeLegacy(\Twig_Environment $env, array $context, $name, array $variables = array(), $withContext = true, $ignoreMissing = false)
{
$fqcn = // determine the class name
$instance = new fqcn();
$template = $instance->getTemplateName();
$variables = array_merge($instance->getVariables(), $variables)
return twig_include($env, $context, $template, $variables, $withContext, $ignoreMissing);
}https://stackoverflow.com/questions/31916251
复制相似问题