基于路径的Twig重载

This is a bit complicated to explain. My use-case is as follows:

Let's say I have the following filesystem structure:

/client/name/web/dashboard.twig <- extends dashboard.twig - file might not exist
/app/name/web/dashboard.twig    <- extends dashboard.twig - file might not exist
/web/dashboard.twig             <- extends layout.twig    - file always exists
/web/layout.twig                <- the base template      - file always exists

Assuming I run $twig->render('dashboard.twig');, I want it to start with the topmost dashboard.twig and keep on going sequentially as in the order specified above.

The current problem is that twig ends up in an infinite loop trying to load the first template file each time. In the recipes section, there's an example to avoid this which makes use paths. This cannot work in my case because of several issues:

  1. The developer of the /client/name/web/dashboard.twig should not be aware of the /app/name/web/dashboard.twig file.
  2. It's still not possible to identify the name path segment and as such, the path concept can't work.

The only solution I can think of is to somehow plug into twig and tell it to "pop out" template files as soon as they're loaded, to eliminate the infinite loop.

This part of the API docs seems useful: http://twig.sensiolabs.org/api/master/Twig_Loader_Filesystem.html

Thanks to an answer from Charles, I've been able to find a solution to my problem.

The main idea is two overload the "extends" Twig tag with code that adds file names of extended files to the name which is later on passed to the loader.