My goal is to look for "webp" in the client HTTP_ACCEPT header in order to determine if I can serve WebP images. I chose this approach rather than using the WebP module because I thought it would be simpler since I'm using a custom twig, trying to serve WebP background images in addition to images w/in img tags and lazy loading.
In my .theme I have:
function mytheme_preprocess_node__some_content_type(&$variables){
if( isset($_SERVER['HTTP_ACCEPT']) ){
$accept_header = $_SERVER['HTTP_ACCEPT'];
if (str_contains($accept_header, 'webp')) {
$variables['browser_can_use_webp'] = true;
} else {
$variables['browser_can_use_webp'] = false;
}
} else {
$variables['browser_can_use_webp'] = false;
}
$variables['#cache']['contexts'][] = 'session';
}
then in my template I'm setting a var with correct img file url something like so:
{# IS THERE A WEBP VERSION AND CAN THE BROWSER RENDER IT #}
{% if node.field_cpt_bck_img_wp.entity.fileuri is not null and browser_can_use_webp == true %}
{% set compBackgroundImageSource = file_url(node.field_cpt_bck_img_wp.entity.fileuri) %}
{% set compBackgroundImageSourceAlt = node.field_cpt_bck_img_wp.alt %}
{% else %} ...
I'm then passing the img file url to client side javascript via a data attribute and handling it there.
My intent with this bit in my .theme:
$variables['#cache']['contexts'][] = 'session';
was to cause the preprocess to set browser_can_use_webp with each new client session but this isn't working. If the relevant node is served to a browser that can accept webp the value of browser_can_use_webp will remain true even if a new session is started by a client that can't.
I've read other threads on the stack exchange and I've read up on the cache api but haven't been able to work out the solution.
Something else I tried was creating a custom module with a new RequestListener class and adding it as a service. I then set my variable in settings.php and made it globally available to twigs via my listener. This worked in the sense that the variable was globally available to my twigs but it did not resolve the cache problem.
Any help would be appreciated.
Internal Page Cache
module is enabled, cache contexts are not re-evaluated for anonymous users.session
doesn't seem to be the correct context. Drupal has a specific cache context for request headers:headers:Accept