Add a way to stream template rendering

This commit is contained in:
Fabien Potencier
2024-12-16 13:46:21 +01:00
parent c72b50434d
commit 1915ee2812
3 changed files with 42 additions and 6 deletions
+1 -1
View File
@@ -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)
+25 -5
View File
@@ -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
+16
View File
@@ -30,6 +30,22 @@ final class TemplateWrapper
) {
}
/**
* @return iterable<scalar|\Stringable|null>
*/
public function stream(array $context = []): iterable
{
yield from $this->template->yield($context);
}
/**
* @return iterable<scalar|\Stringable|null>
*/
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);