1

I have a module that adds functionality to the front-end. The feature can be turned on or off via the configuration page of the module.

I pass the settings to the frontend in the HTML preprocess function using #attached. Simplified, the code looks like this:

function my_module_preprocess_html(&$variables) {
  $config = \Drupal::config('my_module.settings');
  $settings = ['enabled' => $config->get('enabled')];
  $variables['#attached']['drupalSettings']['my_module'] = $settings;
}

This approach is suggested here:

https://docs.acquia.com/tutorials/fast-track-drupal-8-coding/add-custom-variable-drupalsettings/

It works fine when logged in, but for anonymous users changing the setting from the module's configuration page does nothing until I clear caches (as, I assume, the drupalSettings variable is defined within the HTML that makes up the page)

So, my question:

  • Is there a way to ensure the settings are fresh with each page load (without disabling the entire page cache, of course), or
  • Should I refresh the cache whenever the module's configuration form is submitted? If so, what's the most efficient way to do that? (I've noticed a full cache clear is far slower on D8 than it was in D7)
2
  • 1
    This is probably a bit unclear as to get a good answer. I think someone might need to know more about your render array that you're attaching to. The concept you're looking for in Drupal 8 is regarding cache contexts and tags: drupal.org/docs/8/api/cache-api. Depending on what you're doing there may be an appropriate cache tag/context or be able to disable only the cache for that part of the render array with max-age.
    – mradcliffe
    Commented Jan 24, 2019 at 22:30
  • 1
    I've updated the code to show the full context.
    – Geat
    Commented Jan 24, 2019 at 22:37

1 Answer 1

3

Okay, I found the answer. It was as simple as adding this to $variables:

$variables['#cache']['tags'] = $config->getCacheTags();

My question is basically a duplicate of this:

How do I avoid having to clear the cache when changing a module configuration parameter?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.