max-age render array drupal 8

This is all done from the render array itself. The nitty gritty details are documented in Cacheability of render arrays.

In your case, you need to do something like

return [
  '#markup' => $this->t($pageContent),
  '#cache' => [
    'max-age' => 86400, // one day in seconds
  ],
];

This uses the #cache entry for the render array, and sets the max-age to be one day. This is where you would also add in your cache contexts.

As a side note, try to avoid using '#markup'. Use themeable elements, either though code or Twig.
-------------------------
Note that #max-age doesn't apply to the anonymous page cache. Your only easy option there is to disable that completely on those pages with "Drupal::service('page_cache_kill_switch')->trigger();". +1 to using proper #type and #theme render elements, not one big #markup. Especially don't just put all of that through t().
------------------------

原文地址:https://www.cnblogs.com/qinqiu/p/8657375.html