diff --git a/core/themes/engines/twig/twig.engine b/core/themes/engines/twig/twig.engine
index f3a8e176e536ae24cf3cb1a0ef0b177b916e4eca..45a95cae786326c6f714c7d9e7b7ccdcd1fc60b1 100644
--- a/core/themes/engines/twig/twig.engine
+++ b/core/themes/engines/twig/twig.engine
@@ -29,14 +29,8 @@ function twig_extension() {
 function twig_render_template($template_file, array $variables) {
   /** @var \Twig\Environment $twig_service */
   $twig_service = \Drupal::service('twig');
-  $output = [
-    'debug_prefix' => '',
-    'debug_info' => '',
-    'rendered_markup' => '',
-    'debug_suffix' => '',
-  ];
   try {
-    $output['rendered_markup'] = $twig_service->load($template_file)->render($variables);
+    $rendered_markup = $twig_service->load($template_file)->render($variables);
   }
   catch (RuntimeError $e) {
     // In case there is a previous exception, re-throw the previous exception,
@@ -49,6 +43,13 @@ function twig_render_template($template_file, array $variables) {
     throw $e;
   }
   if ($twig_service->isDebug()) {
+    $output = [
+      'debug_prefix' => '',
+      'debug_info' => '',
+      'rendered_markup' => $rendered_markup,
+      'debug_suffix' => '',
+    ];
+
     $output['debug_prefix'] .= "\n\n<!-- THEME DEBUG -->";
     $output['debug_prefix'] .= "\n<!-- THEME HOOK: '" . Html::escape($variables['theme_hook_original']) . "' -->";
     // If there are theme suggestions, reverse the array so more specific
@@ -110,7 +111,8 @@ function twig_render_template($template_file, array $variables) {
     }
     $output['debug_info']   .= "\n<!-- " . $template_override_status_output . " from '" . Html::escape($template_file) . "' -->\n";
     $output['debug_suffix'] .= "\n<!-- " . $template_override_suffix_output . " from '" . Html::escape($template_file) . "' -->\n\n";
+    // This output has already been rendered and is therefore considered safe.
+    return Markup::create(implode('', $output));
   }
-  // This output has already been rendered and is therefore considered safe.
-  return Markup::create(implode('', $output));
+  return Markup::create($rendered_markup);
 }