We have a block (myblock) that is only displayed on 4/5 content types. When a cookie, mycookie, is set and has a value of allow, I want to load the block on the page, but if the value is not set to allow, then I want to remove it from the page. The cookie is set through a third party Javascript library.

How to remove block based on cookie value?


  1. Under block layout, we load the block on 4/5 content types.
  2. Using twig template (myblock--name.html.twig), we add some css to the myblock
  • Try this, it adds conditions for cookies and some other things. Bear in mind you'll need to make sure the internal page cache module is disabled if you want it to work for anonymous users
    – Clive
    Jul 5, 2018 at 18:40

1 Answer 1


I'll assume this is not a block plugin, right (or at least you dont have access to modify it)? If it is or you can modify it, you should add the logic below to your build() method inside your block class.

Is the cookie you're looking for generated from Drupal? Assuming it is, you should be able to do something like this:

HOOK_preprocess_block__myblock__name(&variables) {
  if (!\Drupal::request()->cookies->get('mycookie') == 'allow') {
    $variables = [];
  // Don't forget about cache context for cookie!
  $variables['#cache']['contexts'][] = 'cookies:mycookie'
  • no, the cookie is from a third party JS library. however, i think i am getting closer using hook_preprocess_block Jul 6, 2018 at 16:18

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.