Skip to content

[TwigComponent] Twig "use_yield" compatibility #1487

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/TwigComponent/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"symfony/deprecation-contracts": "^2.2|^3.0",
"symfony/event-dispatcher": "^5.4|^6.0|^7.0",
"symfony/property-access": "^5.4|^6.0|^7.0",
"twig/twig": "~3.8.0"
"twig/twig": "^3.8"
},
"require-dev": {
"symfony/console": "^5.4|^6.0|^7.0",
Expand Down
55 changes: 33 additions & 22 deletions src/TwigComponent/src/Twig/ComponentNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,22 @@
namespace Symfony\UX\TwigComponent\Twig;

use Symfony\UX\TwigComponent\BlockStack;
use Twig\Attribute\YieldReady;
use Twig\Compiler;
use Twig\Environment;
use Twig\Extension\CoreExtension;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Node;
use Twig\Node\NodeOutputInterface;

/**
* @author Fabien Potencier <fabien@symfony.com>
* @author Kevin Bond <kevinbond@gmail.com>
*
* @internal
*/
final class ComponentNode extends Node
#[YieldReady]
final class ComponentNode extends Node implements NodeOutputInterface
{
public function __construct(string $component, string $embeddedTemplateName, int $embeddedTemplateIndex, ?AbstractExpression $props, bool $only, int $lineno, string $tag)
{
Expand Down Expand Up @@ -64,24 +68,25 @@ public function compile(Compiler $compiler): void
->string($this->getAttribute('component'))
->raw(', ')
->raw($twig_to_array)
->raw('(')
;
->raw('(');
$this->writeProps($compiler)
->raw(')')
->raw(");\n")
;
->raw(");\n");

$compiler
->write('if (null !== $preRendered) {')
->raw("\n")
->indent()
->write('echo $preRendered;')
->raw("\n")
->indent();
if (method_exists(Environment::class, 'useYield')) {
$compiler->write('yield from $preRendered; ');
} else {
$compiler->write('echo $preRendered; ');
}
$compiler->raw("\n")
->outdent()
->write('} else {')
->raw("\n")
->indent()
;
->indent();

/*
* Block 2) Create the component & return render info
Expand All @@ -97,17 +102,15 @@ public function compile(Compiler $compiler): void
->string($this->getAttribute('component'))
->raw(', ')
->raw($twig_to_array)
->raw('(')
;
->raw('(');
$this->writeProps($compiler)
->raw('), ')
->raw($this->getAttribute('only') ? '[]' : '$context')
->raw(', ')
->string(TemplateNameParser::parse($this->getAttribute('embedded_template')))
->raw(', ')
->raw($this->getAttribute('embedded_index'))
->raw(");\n")
;
->raw(");\n");
$compiler
->write('$embeddedContext = $preRenderEvent->getVariables();')
->raw("\n")
Expand All @@ -121,8 +124,7 @@ public function compile(Compiler $compiler): void
// happens to contain a {% component %} tag. So we don't need to worry
// about trying to allow a specific embedded template to be targeted.
->write('$embeddedContext["__parent__"] = $preRenderEvent->getTemplate();')
->raw("\n")
;
->raw("\n");

/*
* Block 3) Add & update the block stack
Expand All @@ -143,14 +145,17 @@ public function compile(Compiler $compiler): void
->string('outerBlocks')
->raw(']->convert($blocks, ')
->raw($this->getAttribute('embedded_index'))
->raw(");\n")
;
->raw(");\n");

/*
* Block 4) Render the component template
*
* This will actually render the child component template.
*/
if (method_exists(Environment::class, 'useYield') && $compiler->getEnvironment()->useYield()) {
$compiler
->write('yield from ');
}
$compiler
->write('$this->loadTemplate(')
->string($this->getAttribute('embedded_template'))
Expand All @@ -160,10 +165,16 @@ public function compile(Compiler $compiler): void
->repr($this->getTemplateLine())
->raw(', ')
->string($this->getAttribute('embedded_index'))
->raw(')')
->raw('->display($embeddedContext, $embeddedBlocks);')
->raw("\n")
;
->raw(')');

if (method_exists(Environment::class, 'useYield') && $compiler->getEnvironment()->useYield()) {
$compiler->raw('->unwrap()->yield(');
} else {
$compiler->raw('->display(');
}
$compiler
->raw('$embeddedContext, $embeddedBlocks')
->raw(");\n");

$compiler->write('$this->extensions[')
->string(ComponentExtension::class)
Expand Down
21 changes: 19 additions & 2 deletions src/TwigComponent/src/Twig/PropsNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\UX\TwigComponent\Twig;

use Twig\Attribute\YieldReady;
use Twig\Compiler;
use Twig\Node\Node;

Expand All @@ -19,6 +20,7 @@
*
* @internal
*/
#[YieldReady]
class PropsNode extends Node
{
public function __construct(array $propsNames, array $values, $lineno = 0, ?string $tag = null)
Expand Down Expand Up @@ -47,35 +49,50 @@ public function compile(Compiler $compiler): void

$compiler
->write('$propsNames[] = \''.$name.'\';')
->write("\n")
->write('$context[\'attributes\'] = $context[\'attributes\']->remove(\''.$name.'\');')
->write("\n")
->write('if (!isset($context[\''.$name.'\'])) {');

if (!$this->hasNode($name)) {
$compiler
->indent()
->write('throw new \Twig\Error\RuntimeError("'.$name.' should be defined for component '.$this->getTemplateName().'");')
->write('}');
->write("\n")
->outdent()
->write('}')
->write("\n");

continue;
}

$compiler
->indent()
->write('$context[\''.$name.'\'] = ')
->subcompile($this->getNode($name))
->raw(";\n")
->write('}');
->outdent()
->write('}')
->write("\n");
}

$compiler
->write('$attributesKeys = array_keys($context[\'attributes\']->all());')
->raw("\n")
->write('foreach ($context as $key => $value) {')
->raw("\n")
->indent()
->write('if (in_array($key, $attributesKeys) && !in_array($key, $propsNames)) {')
->raw("\n")
->indent()
->raw('unset($context[$key]);')
->raw("\n")
->outdent()
->write('}')
->raw("\n")
->outdent()
->write('}')
->raw("\n")
;

// overwrite the context value if a props with a similar name and a default value exist
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
<twig:DivComponent6/>

<twig:DivComponent6>Override content<twig:block name="foo">Override foo</twig:block></twig:DivComponent6>
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
<twig:table caption='data table' :headers='["key", "value"]' :data='[[1, 2], [3, 4]]'>
<twig:block name="th">custom th ({{ parent() }})</twig:block>
<twig:block name="td">custom td ({{ parent() }})</twig:block>

<twig:block name="footer">
My footer
</twig:block>
</twig:table>
</twig:table>
1 change: 0 additions & 1 deletion src/TwigComponent/tests/Integration/ComponentLexerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ public function testComponentSyntaxOpenTags(): void
public function testComponentSyntaxSelfCloseTags(): void
{
$output = self::getContainer()->get(Environment::class)->render('tags/self_close_tag.html.twig');

$this->assertStringContainsString('propA: 1', $output);
$this->assertStringContainsString('propB: hello', $output);
}
Expand Down
Loading