Skip to content

Commit

Permalink
feature #936 [TwigComponent] Add variable to refer outer scope when r…
Browse files Browse the repository at this point in the history
…endering 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
  • Loading branch information
weaverryan committed Sep 27, 2023
2 parents 36c1aee + e618111 commit d993b12
Show file tree
Hide file tree
Showing 9 changed files with 99 additions and 13 deletions.
40 changes: 40 additions & 0 deletions src/TwigComponent/doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,46 @@ When overriding the ``alert_message`` block, you have access to the ``message``
{% endblock %}
{% endcomponent %}
.. versionadded:: 2.12

The ability to refer to the scope of higher components via the ``outerScope`` variable was added in 2.12.

As mentioned before, variables from lower components are merged with those from upper components. When you need
access to some properties or functions from higher components, that can be done via the ``outerScope...`` variable:

.. code-block:: twig
{# templates/SuccessAlert.html.twig #}
{% set name = 'Fabien' %}
{% set message = 'Hello' %}
{% component Alert with { type: 'success', name: 'Bart' } %}
Hello {{ name }} {# Hello Bart #}
{{ message }} {{ outerScope.name }} {# Hello Fabien #}
{{ outerScope.this.someFunction }} {# this refers to SuccessAlert #}
{{ outerScope.this.someProp }} {# references a "someProp" prop from SuccessAlert #}
{% endcomponent %}
You can keep referring to components higher up as well. Just add another ``outerScope``.
Remember though that the ``outerScope`` reference only starts once you're INSIDE the (embedded) component.

.. code-block:: twig
{# templates/FancyProfileCard.html.twig #}
{% component Card %}
{% block header %}
{% component Alert with { message: outerScope.this.someProp } %} {# not yet INSIDE the Alert template #}
{% block content %}
{{ message }} {# same value as below, indirectly refers to FancyProfileCard::someProp #}
{{ outerScope.outerScope.this.someProp }} {# directly refers to FancyProfileCard::someProp #}
{% endblock %}
{% endcomponent %}
{% endblock %}
{% endcomponent %}
Component HTML Syntax
---------------------

Expand Down
3 changes: 3 additions & 0 deletions src/TwigComponent/src/ComponentRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@ private function preRender(MountedComponent $mounted, array $context = []): PreR
// first so values can be overridden
$context,

// keep reference to old context
['outerScope' => $context],

// add the component as "this"
['this' => $component],

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,4 @@
#[AsTwigComponent]
final class DivComponentWrapper
{
public string $divComponentWrapperName = 'bar';

public function someFunction(): string
{
return 'calling DivComponentWrapper';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\TwigComponent\Tests\Fixtures\Component;

use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

/**
* @author Bart Vanderstukken <[email protected]>
*/
#[AsTwigComponent]
final class DivComponentWrapper3
{
public string $divComponentWrapperName = 'bar';

public function someFunction(): string
{
return 'calling DivComponentWrapper';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
I can access my own properties: {{ divComponentName }}.
I can access the id of the Generic Element: {{ id }}.
This refers to the Generic Element: {{ this.someFunction }}.
To access my own functions I can use outerScope.this: {{ outerScope.this.someFunction }}.
I have access to outer context variables like {{ name }}.
{{ block(outerBlocks.content) }}
</twig:GenericElement>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<twig:DivComponent5>
I can access the id from Generic Element as well: {{ id }}.
I can access the properties from DivComponent as well: {{ divComponentName }}.
And of course the properties from DivComponentWrapper: {{ divComponentWrapperName }}.
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 {{ this.someFunction }}.
Calls to outerScope.this will be {{ outerScope.this.someFunction }}.
{{ block(outerBlocks.content) }}
</twig:DivComponent5>
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{% set name = 'Fabien' %}
<twig:DivComponent5>
I can access the id from Generic Element as well: {{ id }}.
I can access the properties from DivComponent as well: {{ divComponentName }}.
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 {{ this.someFunction }}.
</twig:DivComponent5>
<twig:DivComponentWrapper3>
Even I can access the id from Generic Element as well: {{ id }}.
Even I can access the properties from DivComponent as well: {{ divComponentName }}.
Even I can access the properties from DivComponentWrapper as well: {{ divComponentWrapperName }}.
Even I can access the functions of DivComponent via outerScope.this: {{ outerScope.this.someFunction }}.
Since we are nesting two levels deep, calls to outerScope.outerScope.this will be {{ outerScope.outerScope.this.someFunction }}.
</twig:DivComponentWrapper3>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<twig:GenericElement element="div" class="divComponent">
{{ outerScope.this.foo }}
</twig:GenericElement>
Original file line number Diff line number Diff line change
Expand Up @@ -140,15 +140,22 @@ public function testPassingDownBlocksMultipleLevelsNeedsToBeDoneManually(): void

/**
* Rule 12: Blocks defined within an embedded component can access the context of the block they are replacing.
* Rule 13: Blocks defined within an embedded component can access the context of components up the hierarchy (up to their own level) via "outerScope".
*/
public function testBlockDefinitionCanAccessTheContextOfTheDestinationBlocks(): void
{
$this->assertStringContainsStringIgnoringIndentation(
'<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>',
'<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>',
self::getContainer()->get(Environment::class)->render('embedded_component_blocks_context.html.twig')
);
}

public function testAccessingTheHierarchyTooHighThrowsAnException(): void
{
$this->expectExceptionMessage('Key "this" for array with keys "app, __embedded" does not exist.');
self::getContainer()->get(Environment::class)->render('embedded_component_hierarchy_exception.html.twig');
}

public function testANonEmbeddedComponentRendersOuterBlocksEmpty(): void
{
$this->assertStringContainsStringIgnoringIndentation(
Expand Down

0 comments on commit d993b12

Please sign in to comment.