New in Symfony 2.2: Cache support for static pages
December 11, 2012 • Published by Fabien Potencier
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Contributed by
Sebastian Krebs
in #6083.
All websites have some kind of static pages like an about page; a static page being a page that does not need any logic to be rendered. As there is no logic, creating an empty controller for them is simple but cumbersome:
1 2 3 4 5 6 7 8 9 10 11
public function aboutAction()
{
return $this->render('AcmeBundle:Pages:about.html.twig');
}
public function locationAction()
{
return $this->render('AcmeBundle:Pages:location.html.twig');
}
// ...
And then, you need to also reference them in the routing configuration file:
1 2
about: { pattern: /about, defaults: { _controller: 'AcmeBundle:Pages:about' } }
location: { pattern: /location, defaults: { _controller: 'AcmeBundle:Pages:location' } }
... and even if using annotations simplifies things a bit, that is still too much work:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/**
* @Route("/about", name="about")
* @Template
*/
public function aboutAction()
{
return array();
}
/**
* @Route("/location", name="location")
* @Template
*/
public function locationAction()
{
return array();
}
// ...
Instead, you can use the built-in FrameworkBundle:Template:template
controller and configure everything from the routing configuration file
directly:
1 2
about: { pattern: /about, defaults: { _controller: FrameworkBundle:Template:template, template: 'AcmeBundle:Pages:about.html.twig' } }
location: { pattern: /location, defaults: { _controller: FrameworkBundle:Template:template, template: 'AcmeBundle:Pages:location.html.twig' } }
In this configuration, we associate a URL to a template via the
FrameworkBundle:Template:template
controller. This has been working since
2.0, but as of 2.2, you can also set the caching strategy:
1 2 3 4 5 6 7 8
about:
pattern: /about
defaults:
_controller: FrameworkBundle:Template:template
template: 'AcmeBundle:Pages:about.html.twig'
maxAge: 86400
sharedMaxAge: 86400
private: false
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
thanx
a good practice !
https://github.com/symfony/symfony-docs/pull/2002
But if this template extends ::base.html.twig that contain username logged in user,
will it cache all html output as seen by user in their browser,
or just content from this template ?
Thanks
always helping to make life easier