0

In search result page I need to change url of title field based on permission assigned to user . If user has permission then show url 1 else show url 2 .

We need to cache all renderable array. I am creating

$data = [
  '#type' => 'link',
  ' #href' => $url, 
]

I am confused with cache context and cache tags.

Please suggest which one to use?

1 Answer 1

2

Cache context - https://www.drupal.org/docs/8/api/cache-api/cache-contexts - is how the cached content varies. In your case you want it to vary - be different for - users based on if they have a permission or not. i.e. you want it to be cached one way if they have the permission, and another way if they don't have the permission. So you probably want user.permissions:<your_permission>.

Cache contexts need to be something Drupal can work out before it gets to the level where it's rendering content and etc so that's why you can have a context on route (cheap to inspect because Apache just gives it to you) but not node (expensive to vary on because to work out the node Drupal needs to run SQL) - because hopefully Drupal can just serve content out of cache before it even gets to the point of working out if the current route matches a node in the database or not.

Cache tags - https://www.drupal.org/docs/8/api/cache-api/cache-tags - are for what your cached data is dependent on. In your case, URL probably points to something right? So if it points to e.g. a node, your cache tag would be node:<nid>, and Drupal will know that if node nid ever changes it should delete those cache entries, because the URL might have changed.

You shouldn't just manually set the cache tag to node:<nid> though - the more generic way to do it is to use addCacheableDependency.

1
  • 1
    Great answer, BTW the context is already set as default, see core.services.yml: renderer.config: required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']
    – 4uk4
    Commented Nov 10, 2017 at 7:32

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.