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


转载于:https://my.oschina.net/imot/blog/221858

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值