![](/img/trans.png)
[英]Symfony and Twig templates. How to dynamically extend a template or extend nothing?
[英]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
或包含此字符串的注釋時,您必須處理雙引號和單引號等問題而不包含模板(不太可能的情況)。
您可以通過使用合適的正則表達式而不是字符串作為$finder
的contains()
函數的參數來處理此問題(尤其是使用引號)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.