Symfony2CookBook:如何将变量注入全部模板(如全局变量)

Sometimes you want a variable to be accessible to all the templates you use. This is possible inside your app/config/config.yml file:
有时您希望有个变量能够被您所使用的所有模板访问,这可以在您app/config/config.yml文件中设定:

 
 
  1. # app/config/config.yml 
  2. twig: 
  3.     # ... 
  4.     globals: 
  5.         ga_tracking: UA-xxxxx-x 

Now, the variable ga_tracking is available in all Twig templates:
现在,变量ga_tracking可以被所有Twig模板访问:

 
 
  1. <p>Our google tracking code is: {{ ga_tracking }} </p> 

It's that easy! You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:
这很容易!您也可以利用内建的服务参数系统,该系统可以让您隔离或重用该值:

 
 
  1. ; app/config/parameters.yml 
  2. [parameters] 
  3.     ga_tracking: UA-xxxxx-x
 
 
  1. # app/config/config.yml 
  2. twig: 
  3.     globals: 
  4.         ga_tracking: %ga_tracking% 

The same variable is available exactly as before.
该变量同先前完全相同。

More Complex Global Variables
更复杂的全局变量

If the global variable you want to set is more complicated - say an object - then you won't be able to use the above method. Instead, you'll need to create a Twig Extension and return the global variable as one of the entries in the getGlobals method.
如果您要设置的全局变量更复杂(如一个对象),那么您将无法使用上述方法。相反,您需要创建一个Twig扩展并返回全局变量。该全局变量作为getGlobals方法返回的全局变量列表中的成员。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值