diff --git a/CHANGELOG b/CHANGELOG index e0bb7953f4..2411ca591a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,6 @@ # 3.18.0 (2024-XX-XX) - * n/a + * Add a way to stream template rendering (`TemplateWrapper::stream()` and `TemplateWrapper::streamBlock()` ) # 3.17.1 (2024-12-12) diff --git a/doc/api.rst b/doc/api.rst index 1842771334..0b35c4cc36 100644 --- a/doc/api.rst +++ b/doc/api.rst @@ -40,15 +40,18 @@ templates from a database or other resources. the evaluated templates. For such a need, you can use any available PHP cache library. -Rendering Templates -------------------- +Loading Templates +----------------- -To load a template from a Twig environment, call the ``load()`` method which +To load a template, call the ``load()`` method on a Twig environment which returns a ``\Twig\TemplateWrapper`` instance:: $template = $twig->load('index.html'); -To render the template with some variables, call the ``render()`` method:: +Rendering Templates +------------------- + +To render a template with some variables, call the ``render()`` method:: echo $template->render(['the' => 'variables', 'go' => 'here']); @@ -56,7 +59,7 @@ To render the template with some variables, call the ``render()`` method:: The ``display()`` method is a shortcut to output the rendered template. -You can also load and render the template in one fell swoop:: +You can also load and render the template directly via the Environment:: echo $twig->render('index.html', ['the' => 'variables', 'go' => 'here']); @@ -65,6 +68,23 @@ If a template defines blocks, they can be rendered individually via the echo $template->renderBlock('block_name', ['the' => 'variables', 'go' => 'here']); +Streaming Templates +------------------- + +.. versionadded:: 3.18.0 + +To stream a template, call the ``stream()`` method`:: + + $template->stream(['the' => 'variables', 'go' => 'here']); + +To stream a specific template block, call the ``streamBlock()`` method:: + + $template->streamBlock('block_name', ['the' => 'variables', 'go' => 'here']); + +.. note:: + + The ``stream()`` and ``streamBlock()`` methods return an iterable. + .. _environment_options: Environment Options diff --git a/src/TemplateWrapper.php b/src/TemplateWrapper.php index 135c59188c..5528037a60 100644 --- a/src/TemplateWrapper.php +++ b/src/TemplateWrapper.php @@ -30,6 +30,22 @@ public function __construct( ) { } + /** + * @return iterable + */ + public function stream(array $context = []): iterable + { + yield from $this->template->yield($context); + } + + /** + * @return iterable + */ + public function streamBlock(string $name, array $context = []): iterable + { + yield from $this->template->yieldBlock($name, $context); + } + public function render(array $context = []): string { return $this->template->render($context);