ArrayLoader.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /*
  3. * This file is part of Mustache.php.
  4. *
  5. * (c) 2012 Justin Hileman
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * Mustache Template array Loader implementation.
  12. *
  13. * An ArrayLoader instance loads Mustache Template source by name from an initial array:
  14. *
  15. * $loader = new ArrayLoader(
  16. * 'foo' => '{{ bar }}',
  17. * 'baz' => 'Hey {{ qux }}!'
  18. * );
  19. *
  20. * $tpl = $loader->load('foo'); // '{{ bar }}'
  21. *
  22. * The ArrayLoader is used internally as a partials loader by Mustache_Mustache instance when an array of partials
  23. * is set. It can also be used as a quick-and-dirty Template loader.
  24. *
  25. * @implements Loader
  26. * @implements MutableLoader
  27. */
  28. class Mustache_Loader_ArrayLoader implements Mustache_Loader, Mustache_Loader_MutableLoader {
  29. /**
  30. * ArrayLoader constructor.
  31. *
  32. * @param array $templates Associative array of Template source (default: array())
  33. */
  34. public function __construct(array $templates = array()) {
  35. $this->templates = $templates;
  36. }
  37. /**
  38. * Load a Template.
  39. *
  40. * @param string $name
  41. *
  42. * @return string Mustache Template source
  43. */
  44. public function load($name) {
  45. if (!isset($this->templates[$name])) {
  46. throw new InvalidArgumentException('Template '.$name.' not found.');
  47. }
  48. return $this->templates[$name];
  49. }
  50. /**
  51. * Set an associative array of Template sources for this loader.
  52. *
  53. * @param array $templates
  54. */
  55. public function setTemplates(array $templates) {
  56. $this->templates = $templates;
  57. }
  58. /**
  59. * Set a Template source by name.
  60. *
  61. * @param string $name
  62. * @param string $template Mustache Template source
  63. */
  64. public function setTemplate($name, $template) {
  65. $this->templates[$name] = $template;
  66. }
  67. }