Twig缓存静态页面

Many people will have missed or overlooked this feature, myself included, however it is a great way to quickly deploy a template to a route. A simple example of this would be creating a privacy page that just informs the user with static information; anything more complicated than this would mean that a Custom Controller would need to be used, as using this method means that you cannot pass any parameters to the twig template. Symfony lets you hook this simple template response in, without creating a Custom Controller. It is a great way to render simple pages without increasing the complexity of your code base.

Caching static pages

99% of the time, rendering a template without a controller produces a static page which is a perfect candidate for caching. This can be easily set within the same config file that you returned the static template with.

An example from the Symfony documentation provides an excellent example of how to include this.

1
2
3
4
5
6
7
acme_privacy:
   path: /privacy         //URL to return the template response
   defaults:
       _controller: FrameworkBundle:Template:template
       template: 'AcmeBundle:Static:privacy.html.twig'                 //template to return
       maxAge: 86400                 //Caching variables
       sharedMaxAge: 86400

The is a very good recipe in the official cookbook about this.

A bit of security

Although the Symfony documentation shows a simple example with the privacy page which would work for most websites, some websites are locked down with login systems for security. The standard login form can still be used for this. The static template route could be set to authenticated users only; for something like documentation of the system, it can be locked down to only authenticated users.

1
2
3
4
5
6
7
8
9
10
11
12
//Security.ymlaccess_control:- { path: /.*, roles: IS_AUTHENTICATED_FULLY } 
//Routing.ymldocumentation:
   path: /documentation
   defaults:
       _controller: DocumenationBundle:Template:template
       template: DocumenationBundle:Static:documentation.html.twig'
       maxAge: 86400
       sharedMaxAge: 86400

The Security.yml shows that any url other than the root of the site requires the user to be authenticated fully. In routing.yml it shows which path should return the documentation twig template page. Its a very simple example but it shows how a static template can be locked down to authenticated users only.

- See more at: http://www.screenfony.com/blog/how-to-render-static-pages-with-symfony#sthash.jE41bkHH.dpuf


你可能感兴趣的:(Twig缓存静态页面)