PhpEngineTheme.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bundle\FrameworkBundle\Form;
  11. use Symfony\Component\Form\Exception\FormException;
  12. use Symfony\Component\Form\Renderer\Theme\FormThemeInterface;
  13. use Symfony\Component\Templating\PhpEngine;
  14. /**
  15. * Renders a Form using the PHP Templating Engine.
  16. *
  17. * Each field is rendered as slot of a template.
  18. *
  19. * @author Benjamin Eberlei <kontakt@beberlei.de>
  20. */
  21. class PhpEngineTheme implements FormThemeInterface
  22. {
  23. /**
  24. * @var array
  25. */
  26. static protected $cache = array();
  27. /**
  28. * @var PhpEngine
  29. */
  30. private $engine;
  31. /**
  32. * @var string
  33. */
  34. private $template;
  35. /**
  36. * @param PhpEngine $engine
  37. */
  38. public function __construct(PhpEngine $engine, $template = null)
  39. {
  40. $this->engine = $engine;
  41. $this->template = $template;
  42. }
  43. public function render($field, $section, array $parameters)
  44. {
  45. if ($template = $this->lookupTemplate($field."_".$section)) {
  46. return $this->engine->render($template, $parameters);
  47. } else if ($template = $this->lookupTemplate($section)) {
  48. return $this->engine->render($template, $parameters);
  49. } else {
  50. throw new FormException(sprintf('The form theme is missing the "%s" template file.', $section));
  51. }
  52. }
  53. protected function lookupTemplate($templateName)
  54. {
  55. if (isset(self::$cache[$templateName])) {
  56. return self::$cache[$templateName];
  57. }
  58. $template = (($this->template) ? ($this->template.":") : "") . $templateName.'.html.php';
  59. if (!$this->engine->exists($template)) {
  60. $template = false;
  61. }
  62. self::$cache[$templateName] = $template;
  63. return $template;
  64. }
  65. public function attributes(array $attribs)
  66. {
  67. $html = '';
  68. foreach ($attribs as $k => $v) {
  69. $html .= $this->engine->escape($k) . '="' . $this->engine->escape($v) .'" ';
  70. }
  71. return $html;
  72. }
  73. }