Skip to content

Commit

Permalink
minor #2456 [TwigComponent] Document about unwanted behavior with `Ex…
Browse files Browse the repository at this point in the history
…poseInTemplate` and computed methods (Kocal)

This PR was merged into the 2.x branch.

Discussion
----------

[TwigComponent] Document about unwanted behavior with `ExposeInTemplate` and computed methods

| Q             | A
| ------------- | ---
| Bug fix?      | no
| New feature?  | no <!-- please update src/**/CHANGELOG.md files -->
| Issues        | Fix #... <!-- prefix each issue number with "Fix #", no need to create an issue if none exist, explain below instead -->
| License       | MIT

<!--
Replace this notice by a description of your feature/bugfix.
This will help reviewers and should be a good start for the documentation.

Additionally (see https://symfony.com/releases):
 - Always add tests and ensure they pass.
 - For new features, provide some code snippets to help understand usage.
 - Features and deprecations must be submitted against branch main.
 - Changelog entry should follow https://symfony.com/doc/current/contributing/code/conventions.html#writing-a-changelog-entry
 - Never break backward compatibility (see https://symfony.com/bc).
-->

As spotted when working on my application, the following code triggers two times the methods `transactions()` because of the presence of `#[ExposeInTemplate]` (because before I used `transactions` instead of `computed.transactions`):

```php
	#[ExposeInTemplate]
    public function transactions(): array
    {
        // SQL query to database
    }
```

```twig
{{ computed.transactions|length }}
```

When I remove `#[ExposeInTemplate]`, then only one SQL query is made.

Commits
-------

16cd48a [TwigComponent] Document about unwanted behavior with ExposeInTemplate and computed methods
  • Loading branch information
Kocal committed Dec 22, 2024
2 parents c3ee75b + 16cd48a commit cddafa8
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/TwigComponent/doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ use the full path of the template where the macro is defined:
<twig:Alert>
{# ❌ this won't work #}
{% from _self import message_formatter %}

{# ✅ this works as expected #}
{% from 'path/of/this/template.html.twig' import message_formatter %}

Expand Down Expand Up @@ -1553,6 +1553,12 @@ are called additional times, the cached value is used.
Computed methods only work for component methods with no required
arguments.

.. tip::

Ensure to not use the ``ExposeInTemplate`` attribute on a computed method,
otherwise the method will be called twice instead of only once, leading to
unnecessary overhead and potential performance issues.

Events
------

Expand Down

0 comments on commit cddafa8

Please sign in to comment.