StringTemplateTrait.php 2.1 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 CakePHP(tm) v 3.0.0
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. namespace Cake\View\Helper;
  16. use Cake\View\StringTemplate;
  17. /**
  18. * Adds string template functionality to any class by providing methods to
  19. * load and parse string templates.
  20. */
  21. trait StringTemplateTrait {
  22. /**
  23. * StringTemplate instance.
  24. *
  25. * @var Cake\View\StringTemplate
  26. */
  27. protected $_templater;
  28. /**
  29. * Initializes the StringTemplate class and loads templates
  30. *
  31. * @param array $templates
  32. * @param string $templateClass Class name of the template class to instantiate
  33. * @return void
  34. */
  35. public function initStringTemplates($templates = [], $templateClass = '\Cake\View\StringTemplate') {
  36. $this->_templater = new $templateClass($templates);
  37. if (isset($this->settings['templates'])) {
  38. $this->_templater->load($this->settings['templates']);
  39. }
  40. }
  41. /**
  42. * Get/set templates to use.
  43. *
  44. * @param string|null|array $templates null or string allow reading templates. An array
  45. * allows templates to be added.
  46. * @return void|string|array
  47. */
  48. public function templates($templates = null) {
  49. if ($templates === null || is_string($templates)) {
  50. return $this->_templater->get($templates);
  51. }
  52. return $this->_templater->add($templates);
  53. }
  54. /**
  55. * Format a template string with $data
  56. *
  57. * @param string $name The template name.
  58. * @param array $data The data to insert.
  59. * @return string
  60. */
  61. public function formatTemplate($name, $data) {
  62. return $this->_templater->format($name, $data);
  63. }
  64. /**
  65. * Returns the template engine object
  66. *
  67. * @return StringTemplate
  68. */
  69. public function getTemplater() {
  70. return $this->_templater;
  71. }
  72. }