ThemeRegistryLoader.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Drupal\Core\Template\Loader;
  3. use Drupal\Core\Theme\Registry;
  4. /**
  5. * Loads templates based on information from the Drupal theme registry.
  6. *
  7. * Allows for template inheritance based on the currently active template.
  8. */
  9. class ThemeRegistryLoader extends \Twig_Loader_Filesystem {
  10. /**
  11. * The theme registry used to determine which template to use.
  12. *
  13. * @var \Drupal\Core\Theme\Registry
  14. */
  15. protected $themeRegistry;
  16. /**
  17. * Constructs a new ThemeRegistryLoader object.
  18. *
  19. * @param \Drupal\Core\Theme\Registry $theme_registry
  20. * The theme registry.
  21. */
  22. public function __construct(Registry $theme_registry) {
  23. $this->themeRegistry = $theme_registry;
  24. }
  25. /**
  26. * Finds the path to the requested template.
  27. *
  28. * @param string $name
  29. * The name of the template to load.
  30. * @param bool $throw
  31. * Whether to throw an exception when an error occurs.
  32. *
  33. * @return string
  34. * The path to the template.
  35. *
  36. * @throws \Twig_Error_Loader
  37. * Thrown if a template matching $name cannot be found.
  38. */
  39. protected function findTemplate($name, $throw = TRUE) {
  40. // Allow for loading based on the Drupal theme registry.
  41. $hook = str_replace('.html.twig', '', strtr($name, '-', '_'));
  42. $theme_registry = $this->themeRegistry->getRuntime();
  43. if ($theme_registry->has($hook)) {
  44. $info = $theme_registry->get($hook);
  45. if (isset($info['path'])) {
  46. $path = $info['path'] . '/' . $name;
  47. }
  48. elseif (isset($info['template'])) {
  49. $path = $info['template'] . '.html.twig';
  50. }
  51. if (isset($path) && is_file($path)) {
  52. return $this->cache[$name] = $path;
  53. }
  54. }
  55. if ($throw) {
  56. throw new \Twig_Error_Loader(sprintf('Unable to find template "%s" in the Drupal theme registry.', $name));
  57. }
  58. }
  59. }