LambdaHelper.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /*
  3. * This file is part of Mustache.php.
  4. *
  5. * (c) 2010-2016 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 Lambda Helper.
  12. *
  13. * Passed as the second argument to section lambdas (higher order sections),
  14. * giving them access to a `render` method for rendering a string with the
  15. * current context.
  16. */
  17. class Mustache_LambdaHelper
  18. {
  19. private $mustache;
  20. private $context;
  21. private $delims;
  22. /**
  23. * Mustache Lambda Helper constructor.
  24. *
  25. * @param Mustache_Engine $mustache Mustache engine instance
  26. * @param Mustache_Context $context Rendering context
  27. * @param string $delims Optional custom delimiters, in the format `{{= <% %> =}}`. (default: null)
  28. */
  29. public function __construct(Mustache_Engine $mustache, Mustache_Context $context, $delims = null)
  30. {
  31. $this->mustache = $mustache;
  32. $this->context = $context;
  33. $this->delims = $delims;
  34. }
  35. /**
  36. * Render a string as a Mustache template with the current rendering context.
  37. *
  38. * @param string $string
  39. *
  40. * @return string Rendered template
  41. */
  42. public function render($string)
  43. {
  44. return $this->mustache
  45. ->loadLambda((string) $string, $this->delims)
  46. ->renderInternal($this->context);
  47. }
  48. /**
  49. * Render a string as a Mustache template with the current rendering context.
  50. *
  51. * @param string $string
  52. *
  53. * @return string Rendered template
  54. */
  55. public function __invoke($string)
  56. {
  57. return $this->render($string);
  58. }
  59. /**
  60. * Get a Lambda Helper with custom delimiters.
  61. *
  62. * @param string $delims Custom delimiters, in the format `{{= <% %> =}}`
  63. *
  64. * @return Mustache_LambdaHelper
  65. */
  66. public function withDelimiters($delims)
  67. {
  68. return new self($this->mustache, $this->context, $delims);
  69. }
  70. }