Using cache for twig variables in preprocess function

I implement a menu on a region using a preprocess function to get a link with an anchor for each block of it with a title. I made a preprocess function for region, in my theme, where I test the region machine name.

I first used the $variables[‘elements’][XXX][‘#id’] to load each block, to find out if the label was set to be display. But I quickly discover that on my server, where the cache is on, the $variables[‘elements’] only contain an array of cached render.

I then modify my preprocess hook to use the key of the $variables[‘elements’], witch is finally the block key.

use DrupalblockEntityBlock;  /**  * Implements hook_preprocess_region().  */ function MYTHEME_preprocess_region(&$variables) {   if ($variables['region'] == 'one_page') {     $blocs_menu = array();     foreach ($variables['elements'] as $key => $values) {       if (substr($key, 0, 1) == '#') {         continue;       }       $bloc_object = Block::load($key);       if (is_object($bloc_object)) {         $bloc_settings = $bloc_object->get('settings');         if ($bloc_settings['label_display']) {           $blocs_menu[] = array(               'id' => $key,               'label' => $bloc_settings['label'],           );         }       }     }     if (count($blocs_menu)) {       $variables['region_menu'] = $blocs_menu;     }   } } 

And in my override file region–one-page.html.twig

{%- if region_menu -%} <nav class="page-nav-anchor">   <ul> {%- for menu in region_menu -%}   <li><a rel="scroll" href="#block-{{ menu['id'] }}">{{ menu['label'] }}</a></li> {%- endfor -%}   </ul> </nav> {%- endif -%} 

Everything is working well, but I would like to improve the concept :

  • Be able to detect if the cache is activated on the project
  • Include in cache my ‘region_menu’ variable, and generate it only when cache have to be rebuild.

If I understand well, the twig template is also cached, then it is maybe just not really necessary to declare the menu if cache is ON ?

The thing is I’m really lost in the D8 cache API. I think I have to deal with the cache tags, because I don’t have a render to cache.

I would appreciate some help, I cannot find some good (and easy) examples on the documentation or in the core modules.

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Using cache for twig variables in preprocess function

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.