How can I disable caching for the front page, programmatically?
1 Answer
I think one way to achieve that is by altering '<front>'
route with a RouteSubscriber service.
mymodule.route_subscriber:
class: Drupal\mymodule\Routing\RouteSubscriber
arguments: ['@config.factory']
tags:
- { name: event_subscriber }
Then in your RouteSubscriber.php class :
/**
* Event subscriber.
*/
namespace Drupal\mymodule\Routing;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Subscribe to KernelEvents::REQUEST events and redirect if user is press.
*/
class RouteSubscriber extends RouteSubscriberBase {
protected $configFactory;
/**
* RouteSubscriber constructor.
* @param ConfigFactoryInterface $config_factory
*/
public function __construct(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}
/**
* {@inheritdoc}
*/
public function alterRoutes(RouteCollection $collection) {
if ($route_front = $collection->get('<front>')) {
$route_front->setOption('no_cache', TRUE);
}
}
}