Avoiding missing image src values when using the Drupal Bamboo Twig module with Stage File Proxy

Bamboo Twig is a great Drupal module which gives you a lot of extra Twig functions to work with Drupal specific functionality in Twig without needing to write a lot of preprocess function code (in PHP).

It allows you to do things like render views, blocks, regions, entities (with view mode), fields, forms and image styles — all just in Twig.

Stage File Proxy is a Drupal module that routes local requests for a Drupal site’s file to a production version of the same site. This is useful for when you pull down a copy of a production site’s database and import it to your local database. Instead of seeing broken references to user-uploaded content that only exists on the production site’s filesystem, Stage File Proxy will catch requests for these missing images locally and either download a copy of the image from the production site, or hotlink to it.

Back to Bamboo Twig now. I find the bamboo_render_image_style function particularly useful, but noticed recently that on my local development version of a site that I was seeing missing images, even with Stage File Proxy enabled.

I put some debugging commands in my Twig files, and it turned out that bamboo_render_image_style(image_uri, 'style_name') was returning NULL instead of a URL, so Stage File Proxy wasn’t getting a chance to catch the request and retrieve the image.

Knowing that without a URL it couldn’t be Stage File Proxy’s fault, I looked into how bamboo_render_image_style works and quite quickly found the problem in bamboo_twig_loader/src/TwigExtension/Render.php:

// Assert the image exist on the file system.
$image_path = $fso->realpath($image->getSource());
if (!is_file($image_path)) {
return NULL;
}

By checking whether the image exists on the file system and returning NULL if it doesn’t, Stage File Proxy isn’t given a chance to catch the request for a missing image, and instead Twig outputs an img or picture element with a missing src value.

I’ve written a quick patch which can be applied via Composer to fix this issue, and the Bamboo Twig maintainers are looking at alternative options.