Skip to content

Commit d993b12

Browse files
committed
feature #936 [TwigComponent] Add variable to refer outer scope when rendering embedded components (sneakyvv)
This PR was squashed before being merged into the 2.x branch. Discussion ---------- [TwigComponent] Add variable to refer outer scope when rendering embedded components | Q | A | ------------- | --- | Bug fix? | no | New feature? | yes | Tickets | | License | MIT This PR's is an alternative approach to the problem stated in #863. Due to the changes proposed in #920, which deals with passing blocks down to nested embedded components, I realized that just being able to access the host (or parent) component isn't sufficient if blocks can be passed down multiple levels deep (as already mentioned in #863 (comment)). This PR adds a proxy object `Hierarchy` which allows this syntax: `Component.php` ```php final class Component { public function scream(int $screamHowHard = 1): string { return 'sf-ux rules' . str_repeat('!', $screamHowHard); } } ``` ```twig {# component.html.twig #} <twig:Foo :someProp="this.something(1)"> {{ someProp }} {{ outerScope.this.something(3) }} </twig:Foo> ``` ```twig {# Foo.html.twig #} <div>{% block content %}{% endblock %}</div> ``` Resulting in ```twig <div> sf-ux rules! sf-ux rules!!! </div> ``` Adding another layer below Foo, would ask for something like ```twig {# component.html.twig #} <twig:Foo> {{ outerScope.outerScope.this.something(3) }} </twig:Foo> ``` to still point to Foo's function. --- ### Questions There's also a `ComputedPropertiesProxy` object. Should we have a cached version of the `Hierarchy` proxy? --- ### NOTE This PR continues on the changes of #920, because having a hierarchy only makes sense if blocks can be passed down multiple times. So #920 may have to be merged first, but if needed, and the `outerScope.this` syntax is preferred over the syntax of #863, I could push my branch that starts of the main branch instead. Edited: using outerScope variable now instead Hierarchy proxy Commits ------- e618111 [TwigComponent] Add variable to refer outer scope when rendering embedded components
2 parents 36c1aee + e618111 commit d993b12

File tree

9 files changed

+99
-13
lines changed

9 files changed

+99
-13
lines changed

src/TwigComponent/doc/index.rst

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -955,6 +955,46 @@ When overriding the ``alert_message`` block, you have access to the ``message``
955955
{% endblock %}
956956
{% endcomponent %}
957957
958+
959+
.. versionadded:: 2.12
960+
961+
The ability to refer to the scope of higher components via the ``outerScope`` variable was added in 2.12.
962+
963+
As mentioned before, variables from lower components are merged with those from upper components. When you need
964+
access to some properties or functions from higher components, that can be done via the ``outerScope...`` variable:
965+
966+
.. code-block:: twig
967+
968+
{# templates/SuccessAlert.html.twig #}
969+
{% set name = 'Fabien' %}
970+
{% set message = 'Hello' %}
971+
{% component Alert with { type: 'success', name: 'Bart' } %}
972+
Hello {{ name }} {# Hello Bart #}
973+
974+
{{ message }} {{ outerScope.name }} {# Hello Fabien #}
975+
976+
{{ outerScope.this.someFunction }} {# this refers to SuccessAlert #}
977+
978+
{{ outerScope.this.someProp }} {# references a "someProp" prop from SuccessAlert #}
979+
{% endcomponent %}
980+
981+
You can keep referring to components higher up as well. Just add another ``outerScope``.
982+
Remember though that the ``outerScope`` reference only starts once you're INSIDE the (embedded) component.
983+
984+
.. code-block:: twig
985+
986+
{# templates/FancyProfileCard.html.twig #}
987+
{% component Card %}
988+
{% block header %}
989+
{% component Alert with { message: outerScope.this.someProp } %} {# not yet INSIDE the Alert template #}
990+
{% block content %}
991+
{{ message }} {# same value as below, indirectly refers to FancyProfileCard::someProp #}
992+
{{ outerScope.outerScope.this.someProp }} {# directly refers to FancyProfileCard::someProp #}
993+
{% endblock %}
994+
{% endcomponent %}
995+
{% endblock %}
996+
{% endcomponent %}
997+
958998
Component HTML Syntax
959999
---------------------
9601000

src/TwigComponent/src/ComponentRenderer.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,9 @@ private function preRender(MountedComponent $mounted, array $context = []): PreR
124124
// first so values can be overridden
125125
$context,
126126

127+
// keep reference to old context
128+
['outerScope' => $context],
129+
127130
// add the component as "this"
128131
['this' => $component],
129132

src/TwigComponent/tests/Fixtures/Component/DivComponentWrapper.php

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,4 @@
1919
#[AsTwigComponent]
2020
final class DivComponentWrapper
2121
{
22-
public string $divComponentWrapperName = 'bar';
23-
24-
public function someFunction(): string
25-
{
26-
return 'calling DivComponentWrapper';
27-
}
2822
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <[email protected]>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\UX\TwigComponent\Tests\Fixtures\Component;
13+
14+
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
15+
16+
/**
17+
* @author Bart Vanderstukken <[email protected]>
18+
*/
19+
#[AsTwigComponent]
20+
final class DivComponentWrapper3
21+
{
22+
public string $divComponentWrapperName = 'bar';
23+
24+
public function someFunction(): string
25+
{
26+
return 'calling DivComponentWrapper';
27+
}
28+
}

src/TwigComponent/tests/Fixtures/templates/components/DivComponent5.html.twig

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
I can access my own properties: {{ divComponentName }}.
33
I can access the id of the Generic Element: {{ id }}.
44
This refers to the Generic Element: {{ this.someFunction }}.
5+
To access my own functions I can use outerScope.this: {{ outerScope.this.someFunction }}.
56
I have access to outer context variables like {{ name }}.
67
{{ block(outerBlocks.content) }}
78
</twig:GenericElement>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<twig:DivComponent5>
2+
I can access the id from Generic Element as well: {{ id }}.
3+
I can access the properties from DivComponent as well: {{ divComponentName }}.
4+
And of course the properties from DivComponentWrapper: {{ divComponentWrapperName }}.
5+
The less obvious thing is that at this level "this" refers to the component where the content block is used, i.e. the Generic Element.
6+
Therefore, functions through this will be {{ this.someFunction }}.
7+
Calls to outerScope.this will be {{ outerScope.this.someFunction }}.
8+
{{ block(outerBlocks.content) }}
9+
</twig:DivComponent5>
Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
{% set name = 'Fabien' %}
2-
<twig:DivComponent5>
3-
I can access the id from Generic Element as well: {{ id }}.
4-
I can access the properties from DivComponent as well: {{ divComponentName }}.
5-
The less obvious thing is that at this level "this" refers to the component where the content block is used, i.e. the Generic Element.
6-
Therefore, functions through this will be {{ this.someFunction }}.
7-
</twig:DivComponent5>
2+
<twig:DivComponentWrapper3>
3+
Even I can access the id from Generic Element as well: {{ id }}.
4+
Even I can access the properties from DivComponent as well: {{ divComponentName }}.
5+
Even I can access the properties from DivComponentWrapper as well: {{ divComponentWrapperName }}.
6+
Even I can access the functions of DivComponent via outerScope.this: {{ outerScope.this.someFunction }}.
7+
Since we are nesting two levels deep, calls to outerScope.outerScope.this will be {{ outerScope.outerScope.this.someFunction }}.
8+
</twig:DivComponentWrapper3>
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<twig:GenericElement element="div" class="divComponent">
2+
{{ outerScope.this.foo }}
3+
</twig:GenericElement>

src/TwigComponent/tests/Integration/EmbeddedComponentTest.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,15 +140,22 @@ public function testPassingDownBlocksMultipleLevelsNeedsToBeDoneManually(): void
140140

141141
/**
142142
* Rule 12: Blocks defined within an embedded component can access the context of the block they are replacing.
143+
* Rule 13: Blocks defined within an embedded component can access the context of components up the hierarchy (up to their own level) via "outerScope".
143144
*/
144145
public function testBlockDefinitionCanAccessTheContextOfTheDestinationBlocks(): void
145146
{
146147
$this->assertStringContainsStringIgnoringIndentation(
147-
'<div class="divComponent">I can access my own properties: foo.I can access the id of the Generic Element: symfonyIsAwesome.This refers to the Generic Element: calling GenericElement.I have access to outer context variables like Fabien.I can access the id from Generic Element as well: symfonyIsAwesome.I can access the properties from DivComponent as well: foo.The less obvious thing is that at this level "this" refers to the component where the content block is used, i.e. the Generic Element.Therefore, functions through this will be calling GenericElement.<span class="foo">The Generic Element default foo block</span></div>',
148+
'<div class="divComponent">I can access my own properties: foo.I can access the id of the Generic Element: symfonyIsAwesome.This refers to the Generic Element: calling GenericElement.To access my own functions I can use outerScope.this: calling DivComponent.I have access to outer context variables like Fabien.I can access the id from Generic Element as well: symfonyIsAwesome.I can access the properties from DivComponent as well: foo.And of course the properties from DivComponentWrapper: bar.The less obvious thing is that at this level "this" refers to the component where the content block is used, i.e. the Generic Element.Therefore, functions through this will be calling GenericElement.Calls to outerScope.this will be calling DivComponent.Even I can access the id from Generic Element as well: symfonyIsAwesome.Even I can access the properties from DivComponent as well: foo.Even I can access the properties from DivComponentWrapper as well: bar.Even I can access the functions of DivComponent via outerScope.this: calling DivComponent.Since we are nesting two levels deep, calls to outerScope.outerScope.this will be calling DivComponentWrapper.<span class="foo">The Generic Element default foo block</span></div>',
148149
self::getContainer()->get(Environment::class)->render('embedded_component_blocks_context.html.twig')
149150
);
150151
}
151152

153+
public function testAccessingTheHierarchyTooHighThrowsAnException(): void
154+
{
155+
$this->expectExceptionMessage('Key "this" for array with keys "app, __embedded" does not exist.');
156+
self::getContainer()->get(Environment::class)->render('embedded_component_hierarchy_exception.html.twig');
157+
}
158+
152159
public function testANonEmbeddedComponentRendersOuterBlocksEmpty(): void
153160
{
154161
$this->assertStringContainsStringIgnoringIndentation(

0 commit comments

Comments
 (0)