2

I need the current path, where my custom block is visible. So, i have written this code

class MyBlock extends BlockBase {

  public function build() {
    $currentPath= \Drupal::service('path.current')->getPath();  
    return array(
        '#markup' => $currentPath,
    );
  }
}

It is displaying the path where it was visible for first time; if I visit node/1, node/2, node/3 consecutively, it will print node/1 every time, because that was what I visited that first.
It might be happening due to block caching, but how do I get the path for the page showing the block?

8

Yes, this is because of block caching. The block is built once for the first request and then will stay in the cache forever, until you clear the cache.

You have to set a cache context on the url path:

'#cache' => ['contexts' => ['url.path']],

Then the block will get a cached version for every path.

| improve this answer | |
2

You can also turn off the cache for certain blocks this way:

'#cache' => ['max-age' => 0];

But it would be better if you can find what is unique in each block and set those as context variables.

https://www.drupal.org/developing/api/8/cache/contexts

For urls alone, there are many variations:

url
  .host
  .query_args
    :key
    .pagers
      :pager_id
  .path
    .parent
  .site
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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