Problem / Motivation
We have a custom Twig extension in our Drupal 10 project. When clearing the cache via the admin interface, it throws the following error:
LogicException: Unable to register extension "Drupal\custom_module\TwigExtension\CustomModuleTwigExtension" as extensions have already been initialized. in Twig\ExtensionSet->addExtension() (line 146 of /var/www/html/vendor/twig/twig/src/ExtensionSet.php).
After debugging, I found that our custom extension is loaded first. Later, _trash_generate_storage_class calls \Drupal::service('twig'), which triggers our custom extension a second time, causing the error.
Despite this, the cache clears correctly, and the site functions without issues. However, the error is confusing and could be misleading for developers, so it’s worth addressing.
Proposed Resolution
In my case, I replaced the call to `\Drupal::service('twig')` with a direct inclusion of the necessary file. This generates the same output as before, ensures that the Trash functionality works as expected, and eliminates the cache-clear error.
This approach may be useful for other Drupal 10 projects experiencing a similar issue with custom Twig extensions.
I’m not certain whether this issue is relevant for Drupal 11, or if it is already counted in other open issues. Therefore, this should be considered a workaround specific to the Drupal 10 case.
| Comment | File | Size | Author |
|---|---|---|---|
| #3 | 3569892-cache-flush-error-in-admin-ui-unable-to-register-twigextension-2.patch | 1.21 KB | terry_kolodiy |
Issue fork trash-3569892
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #2
terry_kolodiy commentedpatch that fixes this issue for me
Comment #3
terry_kolodiy commentedimproved patch
Comment #4
dave reidI have also run into this error, because some of our contrib Twig Extensions (Twig Tweak and Config Pages) call theme alter and module alters in their getFunctions() or getFilters() methods, this causes the theme manager to short-circuit because it hasn't yet determined what the current theme is. Using Twig too early before the request object has been normalized, which might involve entity loading and needing the Trash entity storage class to exist, is bad news. I also support doing string replacement.
I also found that by using the State API to store the class suffix, means that this is geting invalidated every time a `drush cr` is run, because the State API data is wiped when that happens. It would be much better to use the Key Value Storage API, which is designed to be more persistent.
Comment #8
amateescu commentedMerged into 3.x and 3.1.x, thanks!
I really hope that we'll be able to change core to allow intercepting deletes properly, so all this code generation can go away :)