服务方法作为twig全局变量

Séb*_*ien 10 php service global-variables symfony twig

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

我很期待能打电话

{%if portfolio_user%}

在树枝上.我不明白如何将其设置为全局变量,因为我在印象中只能设置固定元素或服务而不是服务方法.

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

谢谢!

Mat*_*teo 14

您可以twig globals variable按如下方式定义自定义服务:

在config.yml中

# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"
    globals:
        myGlobaService: "@acme.demo_portfolio_service"  #The id of your service
Run Code Online (Sandbox Code Playgroud)

使用它是一个Twig文件

{% if myGlobaService.portfolio_user() %}
Run Code Online (Sandbox Code Playgroud)

希望这有帮助


Cer*_*rad 6

一种方法是使用CONTROLLER事件侦听器。我喜欢使用CONTROLLER而不是REQUEST,因为它可以确保所有常规请求侦听器都已完成其工作。

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ProjectEventListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
    return array
    (
        KernelEvents::CONTROLLER => array(
            array('onControllerProject'),
        ),
    );
}
private $twig;
public function __construct($twig)
{
    $this->twig = $twig;
}
public function onControllerProject(FilterControllerEvent $event)
{
    // Generate your data
    $project = ...;

    // Twig global
    $this->twig->addGlobal('project',$project);    
}

# services.yml
cerad_project__project_event_listener:
    class: ...\ProjectEventListener
    tags:
        - { name: kernel.event_subscriber }
    arguments:
        - '@twig'
Run Code Online (Sandbox Code Playgroud)

此处记录了侦听器:http : //symfony.com/doc/current/cookbook/service_container/event_listener.html

另一种方法是完全避免全局分支,而只进行扩展调用。 http://symfony.com/doc/current/cookbook/templating/twig_extension.html

两种方法都行之有效。