StringTemplateTrait.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\View\Helper;
  16. /**
  17. * Adds string template functionality to any class by providing methods to
  18. * load and parse string templates.
  19. */
  20. trait StringTemplateTrait {
  21. /**
  22. * StringTemplate instance.
  23. *
  24. * @var \Cake\View\StringTemplate
  25. */
  26. protected $_templater;
  27. /**
  28. * Get/set templates to use.
  29. *
  30. * @param string|null|array $templates null or string allow reading templates. An array
  31. * allows templates to be added.
  32. * @return void|string|array
  33. */
  34. public function templates($templates = null) {
  35. if ($templates === null || is_string($templates)) {
  36. return $this->templater()->get($templates);
  37. }
  38. $this->templater()->add($templates);
  39. return $this;
  40. }
  41. /**
  42. * Format a template string with $data
  43. *
  44. * @param string $name The template name.
  45. * @param array $data The data to insert.
  46. * @return string
  47. */
  48. public function formatTemplate($name, $data) {
  49. return $this->templater()->format($name, $data);
  50. }
  51. /**
  52. * templater
  53. *
  54. * @return \Cake\View\StringTemplate
  55. */
  56. public function templater() {
  57. if (empty($this->_templater)) {
  58. $class = $this->config('templateClass') ?: 'Cake\View\StringTemplate';
  59. $this->_templater = new $class();
  60. $templates = $this->config('templates');
  61. if ($templates) {
  62. if (is_string($templates)) {
  63. $this->_templater->add($this->_defaultConfig['templates']);
  64. $this->_templater->load($templates);
  65. } else {
  66. $this->_templater->add($templates);
  67. }
  68. }
  69. }
  70. return $this->_templater;
  71. }
  72. }