服务方法作为枝全局变量 [英] service method as twig global variable

查看:138
本文介绍了服务方法作为枝全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的symfony2应用程序中,我有一个getPorfolioUser方法,它返回一个特定的用户变量。



我期待能够调用


{%if portfolio_user%}


我不明白我怎样才能把它设置为一个全局变量,因为从我的印象中我只能设置固定的元素或服务而不是服务的方法。



我是否有义务为此编写扩展名或助手?
这样做的更简单的方法是什么?

谢谢!

解决方案

您可以将定制服务定义为 twig全局变量,如下所示:



在config.yml



 #小枝配置
小枝:
调试:%kernel.debug%
strict_variables:%kernel.debug%
全局变量:
myGlobaService:@ acme.demo_portfolio_service#您的服务的标识



使用它一个树枝文件



  {%if myGlobaService.portfolio_user()% } 

希望得到这个帮助


In my symfony2 application, I have a getPorfolioUser method which return a specific user variable.

I am looking forward to be able to call

{% if portfolio_user %}

in twig. I did not understand how I could set this as a global variable as from the documentation I am under the impression I can only set fixed elements or services but not services' methods.

Am I obliged to write an extension or a helper for that ? What the simpler way of doing this ?

Thanks!

解决方案

You can define your custom service as twig globals variable as follow:

in the config.yml

# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"
    globals:
        myGlobaService: "@acme.demo_portfolio_service"  #The id of your service

Use it a Twig file

{% if myGlobaService.portfolio_user() %}

Hope this help

这篇关于服务方法作为枝全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆