Problem/Motivation

When the TwigExtension service is overridden, #3270148: Provide a mechanism for deprecation of variables used in twig templates uses the wrong class and throws an exception:

The website encountered an unexpected error. Try again later.

Twig\Error\RuntimeError: The "Drupal\Core\Template\TwigExtension" extension is not enabled in "__string_template__d7d7f1a462505651fc222178924da388" at line 1. in Twig\ExtensionSet->getExtension() (line 73 of /var/www/html/vendor/twig/twig/src/ExtensionSet.php).
Twig\Environment->getExtension('\Drupal\Core\Template\TwigExtension') (Line: 40)

Steps to reproduce

  1. Install the latest version of Drupal 11.x using the standard profile.
  2. Install drush.
  3. Run the drush generate command to generate a custom module or hand-code a custom module.
  4. Code the custom module as explained below to override the class in a custom module service provider class.
  5. Enable the custom module.
  6. Navigate to any page that uses Twig and view the fatal error as described above.
/**
 * Modifies the date_formatter service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    if ($container->hasDefinition('twig.extension')) {
      $container->getDefinition('twig.extension')
        ->setClass('Drupal\my_module\Template\TwigExtension');
    }
  }

}

The overridden class can be simply defined.

<?php

namespace Drupal\my_module\Template;

use Drupal\Core\Template\TwigExtension as CoreTwigExtension;

/**
 * class TwigExtension.
 */
class TwigExtension extends CoreTwigExtension {
}

Proposed resolution

Class can be simply defined

Remaining tasks

Review/Commit

User interface changes

N/A

Introduced terminology

N/A

API changes

N/A

Data model changes

N/A

Release notes snippet

TBD

Issue fork drupal-3409549

Command icon 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

douggreen created an issue. See original summary.

douggreen’s picture

StatusFileSize
new844 bytes

Patch attached

douggreen’s picture

Issue summary: View changes
sandeepsingh199’s picture

Status: Active » Needs review
StatusFileSize
new849 bytes

Tried to fixed the #2 issue.

smustgrave’s picture

Status: Needs review » Needs work
Issue tags: +Needs issue summary update, +Needs tests

If going to use patches an interdiff should be provided to show what you changed but one was not or an explanation.

Issue summary is missing proposed solution

Will need test coverage

eliechoufani’s picture

StatusFileSize
new849 bytes

Hello, I had the error

[error] 8924#8924: *155212268 FastCGI sent in stderr: "PHP message: Uncaught PHP Exception Twig\Error\RuntimeError: "The "Drupal\Core\Template\TwigExtension" extension is not enabled." at /home/XXXXX/www/web/themes/contrib/stable/templates/field/time.html.twig line 22"

after I upgraded Drupal to 10.2.1

And I fixed it with the attached patch, maybe it needs more testing.

I am using

"drupal/twig_extender": "5.1.0",
"drupal/twig_extender_extras": "5.1.0",

in my project.

Good luck.

lamp5’s picture

I can confirm. The issue exists after update to Drupal 10.2.2 and when using "drupal/twig_extender": "5.1.0",

bdanin’s picture

Confirmed, the patch in comment #6 fixes this issue for me. I am also running twig_extender.

djsagar’s picture

Issue summary: View changes

Updated summary with list of review tasks.

djsagar’s picture

Issue summary: View changes

Version: 10.2.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

neclimdul’s picture

Replacing a extension sounds pretty dangerous.

The current approach of calling \Drupal::service is functional but seems like a _huge_ performance hit going to the container ever template render.

Does anyone know why the deprecation compiler code was written into the extension? It seems like it might have just been convenient.

If it was important, maybe we can move it to a dedicated "extension" that's not really an extension that just provides this helper?

If the approach isn't important, maybe we can just inline the check. Something like this maybe:


    $compiler->write("isset(\$context['deprecations']) && array_map(");
    $compiler->indent();
    $compiler->write("fn (\$name) =>");
    $compiler->indent();
    $compiler->write(
      "isset(\$context['deprecations'][\$name])",
      "&& \array_key_exists(\$name, \$context)",
      "&& @trigger_error(\$context['deprecations'][\$name], E_USER_DEPRECATED),"
    );
    $compiler->outdent();
    $compiler->subcompile($usedNamesNode);
    $compiler->outdent();
    $compiler->raw(");");

momow changed the visibility of the branch 3409549-new-twig-variable to hidden.

santhosh@21’s picture

This issue exists after drupal upgrade to 10.3.1 from 10.2.7
Patch 6 works for me

mjgruta’s picture

We upgraded from Drupal 10.1 to 10.2.7 and had a WSOD

Twig\Error\RuntimeError: The "Drupal\Core\Template\TwigExtension" extension is not enabled. in Twig\ExtensionSet->getExtension() (line 35 of docroot/core/themes/claro/templates/admin/admin-block-content.html.twig).

We also had an old version of twig_extender.

Applying the patch #6 and using twig_extender 5.1.0 works fine.

arunkumark made their first commit to this issue’s fork.

arunkumark’s picture

Status: Needs work » Needs review
StatusFileSize
new228.17 KB

I created an MR with the #6 patch. I ran the PHPUnit test locally. It is working fine. hope no update in Test cases. I have attached a screenshot for reference.

Screenshot

@smustgrave hope issue summary is fine

smustgrave’s picture

Status: Needs review » Needs work

Was also tagged for tests which are still needed.

scampbell1’s picture

I just tried upgrading to 10.3.6 and am now getting a WSOD. After some googling, I came across this thread (please let me know if it's best if I create a separate issue).

Currently, the error says Twig\Error\RuntimeError: The "Drupal\Core\Template\TwigExtension" extension is not enabled in "core/themes/claro/templates/classy/layout/html.html.twig". in /code/vendor/twig/twig/src/ExtensionSet.php on line 80

However, #6 would not apply for me because my TwigNodeCheckDeprecations.php already written that way.

I, too, am running Twig Extender.

alshami’s picture

StatusFileSize
new1.49 KB

The issue is that the extension is called by class name statically, For the twig_extender module users the extension called is different than the core one, So this patch get the class name from the service itself.

This patch work for ( 10.3.6 )

scampbell1’s picture

Version: 11.x-dev » 10.3.x-dev
StatusFileSize
new739 bytes

I haven't done heavy testing (but am no longer getting a WSOD!) but I used the second part of what alshami wrote in their patch to create one for 10.3.6 since the version of Drupal I got through my web host already has TwigNodeCheckDeprecations.php saying $compiler->write("\Drupal::service('twig.extension')->checkDeprecations(\$context, ");.

There are two versions of the patch: one for the first patch alshami wrote and another for the second. This is the first.

scampbell1’s picture

StatusFileSize
new769 bytes

Patch version #2 attached

karibuplus’s picture

The patch in comment #21 fixes this issue for me after upgrading from 10.3.5 to 10.3.6. I replaced patch at comment #6 with the new patch 3409549-21.patch
I am also running twig_extender.

bdanin’s picture

Once again hit the error Twig\Error\RuntimeError: The "Drupal\Core\Template\TwigExtension" extension is not enabled (see #8) and I replaced the patch I was originally using in #6 with the patch provided in #21, which is working for me in 10.3.6 using twig_extender.

oily’s picture

MR !9765 seems to be the closest to a fix of the two merge requests. The other MR breaks several tests. This MR only breaks one PHPUnit Unit test.

However it does not include a failing test, in fact a test is still required. Also the existing code needs fixed so it does not break any existing tests.

arunkumark’s picture

I tried to fix the TestCase issues but was unable to solve them. I am facing a problem with the test cases for the TWIG render function with arguments replaced.

Inside testFormatDate() $result = $twig->render('{{ time|format_date("html_date") }}', ['time' => $timestamp]);
and testFileUrl()$result = $twig->render('{{ file_url(file) }}', ['file' => 'public://picture.jpg']);.

But I checked by replacing the $compiler->write("\$this->env->getExtension(\\Drupal::service('twig.extension')::class)\n"); with $compiler->write("\$this->env->getExtension('\Drupal\Core\Template\TwigExtension')\n");, then the testcases are working fine.

Trying to solve by below ways on TwigNodeCheckDeprecations.php. But no luck,

1. $compiler->write("\$this->env->getExtension(\Drupal::service('twig.extension')::class)\n");
2. $compiler->write("\$this->env->getExtension(\\Drupal::service('twig.extension')::class)\n");
3. $compiler->write("\$this->env->getExtension(\\" . \Drupal::service('twig.extension')::class) . "\n");
3. $compiler->write("\$this->env->getExtension('\\" . \Drupal::service('twig.extension')::class) . "'\n");

oily changed the visibility of the branch 3409549-twig-deprecation-check to hidden.

oily’s picture

Hi @arunkumark, Which branch are you using for your code changes/ trials? I cannot see any commits?

We probably should hide the other (non-active) branch(es).

ericpugh’s picture

I'm using Drupal 10.3.10, and while patch #21(and others) fixes the fatal error on the site, the patch does not seem to fix the error when using Single-Directory Components module. (which will supposedly be a stable core module in D11)

arunkumark’s picture

@oily am using the 3409549-New-twig-variable-deprecation-check-should-use-a-service-and-not-the-direct-class branch and my MR 9765

douggreen’s picture

StatusFileSize
new746 bytes

Attached is #23 rerolled for core 10.4.x

oways23’s picture

StatusFileSize
new1.49 KB
new1.49 KB

Re-roll patch #23 for drupal 10.4.x.

christina_abboud’s picture

StatusFileSize
new1.5 KB

Re-rolled the patch for Drupal Core 10.3.12

oily’s picture

Version: 10.3.x-dev » 11.x-dev
oily’s picture

We are now using MR's instead of patches. The MR's are made against the 11.x branch and can then be back-ported to other versions.

rohitsharma401 changed the visibility of the branch 3409549-New-twig-variable-deprecation-check-should-use-a-service-and-not-the-direct-class to hidden.

adel-by made their first commit to this issue’s fork.

adel-by’s picture

StatusFileSize
new2.92 KB
new2.92 KB

Patch for Drupal Core 10.4.x (added same changes to ComponentNodeVisitor)

adel-by’s picture

adel-by’s picture

StatusFileSize
new2.92 KB

Please ignore patches from #41
here's a patch that's against 10.4.x (added same changes to ComponentNodeVisitor)

foxy-vikvik’s picture

After applying the patch, SDC components are not functioning as expected.

Twig\Error\RuntimeError: The "Drupal\Core\Template\TwigExtension" extension is not enabled in "theme:footer". in Twig\ExtensionSet->getExtension() (line 80 of /var/www/html/vendor/twig/twig/src/ExtensionSet.php).
efrainh’s picture

#43 works on my setup. I'm now on 10.4.5

The error messages disappeared.

Thanks!

aurélien sqli’s picture

StatusFileSize
new3.18 KB

Get the same error on Drupal 11.2.x, it's related to trans function with variable inside on twig files

Have to do the replacement on TwigNodeTrans file

oily’s picture

Issue summary: View changes

Updated the IS to use the IS template and re-structured and re-wrote the IS accordingly. Fleshed out the steps to reproduce.

oily’s picture

douggreen’s picture

Hiding all patch files, please use MR's

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.