2016-06-21 176 views
2

我的模板由模塊分隔。 並命名爲moduleName:templateName。 該模板將在文件<moduleNameDirectory>/templateName.twig中搜索。樹枝和相關模板

例如:通過我的裝載機(實現Twig_LoaderInterface)處理在extendsinclude

{% extends "firstModule:layout" %} 

{% block content %} 
    {% include "secondModule:inc" %} 
{% endblock %} 

模板名稱。 它的工作原理。

但我不想在模塊本身指定模塊密鑰。

{% extends ":layout" %} 

{% block content %} 
    {% include "secondModule:inc" %} 
{% endblock %} 

:layout與上述模板在同一模塊內。

如何找到加載器方法內的父模板名稱。 或其他方式來解決這個問題(沒有全局狀態)。

+1

不幸的是,裝載機叫做tota如果超出了當前模板的範圍,恐怕您無法知道您需要哪種模板。 –

+0

謝謝你,阿蘭。但也許還有其他方法?例如,擴展模板類。 –

回答

0

我找到了解決方案。 也許它是黑客。

模板的基類是Twig_Template,它有方法loadTemplate($template, $templateName, $line, $index)

  • $template,我們包括
  • $templateName當前模板

和基類可以延長:

http://twig.sensiolabs.org/doc/api.html#environment-options

父名的基礎上,規範化相對模板名稱

abstract class MyBaseTemplate extends \Twig_Template 
{ 
    /** 
    * {@inheritdoc} 
    */ 
    protected function loadTemplate($template, $templateName = null, $line = null, $index = null) 
    { 
     if (substr($template, 0, 1) === ':') { 
      $parent = explode(':', $templateName, 2); 
      if (count($parent) === 1) { 
       throw new \MyTwigException('It is global template'); 
      } 
      $template = $parent[0].$template; 
     }   
     return parent::loadTemplate($template, $templateName, $line, $index); 
    } 
} 

$loader = new Loader(); 
$options = [ 
    'base_template_class' => 'MyBaseTemplate', 
]; 

$env = new \Twig_Environment($loader, $options); 
$template = $env->loadTemplate('mo:page'); 
$content = $template->render($vars);