FilesystemLoader.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace Drupal\Core\Template\Loader;
  3. use Drupal\Core\Extension\ModuleHandlerInterface;
  4. use Drupal\Core\Extension\ThemeHandlerInterface;
  5. /**
  6. * Loads templates from the filesystem.
  7. *
  8. * This loader adds module and theme template paths as namespaces to the Twig
  9. * filesystem loader so that templates can be referenced by namespace, like
  10. * @block/block.html.twig or @mytheme/page.html.twig.
  11. */
  12. class FilesystemLoader extends \Twig_Loader_Filesystem {
  13. /**
  14. * Constructs a new FilesystemLoader object.
  15. *
  16. * @param string|array $paths
  17. * A path or an array of paths to check for templates.
  18. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  19. * The module handler service.
  20. * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
  21. * The theme handler service.
  22. */
  23. public function __construct($paths, ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler) {
  24. parent::__construct($paths);
  25. // Add namespaced paths for modules and themes.
  26. $namespaces = [];
  27. foreach ($module_handler->getModuleList() as $name => $extension) {
  28. $namespaces[$name] = $extension->getPath();
  29. }
  30. foreach ($theme_handler->listInfo() as $name => $extension) {
  31. $namespaces[$name] = $extension->getPath();
  32. }
  33. foreach ($namespaces as $name => $path) {
  34. $this->addPath($path . '/templates', $name);
  35. }
  36. }
  37. /**
  38. * Adds a path where templates are stored.
  39. *
  40. * @param string $path
  41. * A path where to look for templates.
  42. * @param string $namespace
  43. * (optional) A path name.
  44. */
  45. public function addPath($path, $namespace = self::MAIN_NAMESPACE) {
  46. // Invalidate the cache.
  47. $this->cache = [];
  48. $this->paths[$namespace][] = rtrim($path, '/\\');
  49. }
  50. }