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?


2 Answers 2


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.


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.


For urls alone, there are many variations:


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.