Templates fail to load unless cwd is the Drupal root

Created on 11 May 2017, almost 8 years ago
Updated 18 February 2023, about 2 years ago

I am trying to build a system that will render Drupal Twig templates outside of Drupal (using Drupal's Twig engine). When I bootstrap Drupal from anywhere but what would normally be the Drupal root, the ThemeRegistryLoader fails to find the templates.

Steps to reproduce

From outside your Drupal site, put the following PHP code into a file:

use Drupal\Core\DrupalKernel;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;

$drupal_root = '/Users/rfbayliss/Sites/d8';
$autoloader = require $drupal_root.'/autoload.php';
require_once $drupal_root . '/core/includes/bootstrap.inc';
$request = Request::create('/', 'GET', [], [], [], ['SCRIPT_NAME' => $drupal_root . '/index.php']);
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod', FALSE);
Settings::initialize($drupal_root, DrupalKernel::findSitePath($request), $autoloader);
$kernel->boot();
$kernel->preHandle($request);
$kernel->getContainer()->get('twig')->render('confirm-form.html.twig');

You will get an exception, "Unable to find template "confirm-form.html.twig" in the Drupal theme registry." This is because we're using a relative path in ThemeRegistryLoader::findTemplate(), which tries to resolve the filename relative to the working directory. The relevant section:

if ($theme_registry->has($hook)) {
  $info = $theme_registry->get($hook);
  if (isset($info['path'])) {
    $path = $info['path'] . '/' . $name;
  }
  elseif (isset($info['template'])) {
    $path = $info['template'] . '.html.twig';
  }
  if (isset($path) && is_file($path)) {
    return $this->cache[$name] = $path;
  }
}

This is a pretty easy fix though. We already have an app.root parameter in the service container, so we can just inject it into the loader and use it to formulate an absolute path to the template.

Feature request
Status

Needs work

Version

10.1

Component
Theme 

Last updated 2 days ago

Created by

🇺🇸United States rbayliss

Live updates comments and jobs are added and updated live.
  • Needs change record

    A change record needs to be drafted before an issue is committed. Note: Change records used to be called change notifications.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024