繁体   English   中英

如何获取Symfony / Twig中包含模板的模板名称

[英]How get the names of templates where a template is included in Symfony/Twig

我在twig中有一个部分模板,我包含在我的应用程序的不同模板中。

partial.html.twig

<p>My partial template</p>

例如,我可以在另一个模板中使用此模板:

my_template.html.twig

<% include partial.html.twig %>

我的目标是以某种方式动态地获取包含partial.html.twig的所有模板名称。

这可能吗 ?

我也(像Stratadox)怀疑这是否应该是你应该去的,但无论如何你必须得到包含partial.html.twig模板的所有模板,你可以使用Symfony Finder组件,如下所示:

// App/Controller/DefaultController.php
public function foo(){
    $templatesDir = $this->get('kernel')->getProjectDir() . '/templates';
    $finder = new Symfony\Component\Finder\Finder();
    $finder->files()->in($templatesDir)->contains("{% include 'partial.html.twig' %}");
    $templateNames = [];
    foreach ($finder as $template) {
        $templateNames[] = $template->getFilename();
    }
}

现在,您可以使用这些名称做任何您想做的事情。

当然,在包含partial.html.twig或包含此字符串的注释时,您必须处理双引号和单引号等问题而不包含模板(不太可能的情况)。

您可以通过使用合适的正则表达式而不是字符串作为$findercontains()函数的参数来处理此问题(尤其是使用引号)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM