Symfony没有加载运行时Twig扩展

时间:2018-05-27 17:22:57

标签: php symfony twig

我按照Symfony 3.4 docs上的示例,在运行时加载了一个Twig扩展,但它没有加载:我做错了什么?

IN:src / PlotlyBundle / Twig / AppRuntime.php

<?php
namespace PlotlyBundle\Twig;

class AppRuntime
{
    public function __construct()
    {
    }

    public function biDraw()
    {
        return 'awesome text here';
    }
}

IN:src / PlotlyBundle / Resources / config / services.yml

services:
    plotly.twig_runtime:
        class: PlotlyBundle\Twig\AppRuntime
        public: true
        tags:
            - { name: twig.runtime }

IN:src / PlotlyBundle / Twig / AppExtension.php

<?php
namespace PlotlyBundle\Twig;

use PlotlyBundle\Twig\AppRuntime;

class AppExtension extends \Twig_Extension
{
    public function getFunctions()
    {    
        return [
            new \Twig_SimpleFunction(
                'bi_draw',
                array(AppRuntime::class, 'biDraw')
            ),
        ];
    }
}

IN:src / AppBundle / Controller / DashboardController.php

   $twig = $this->get('plotly.twig_runtime');
    return $this->render(
        'dashboard/index.html.twig'
    );

IN:app / Resources / views / dashboard / index.html.twig

{{ bi_draw() }}

1 个答案:

答案 0 :(得分:1)

感谢@Federkun评论我通过自动装配Twig扩展来修复它:

IN:src / PlotlyBundle / Resources / config / services.yml

services:
    # default configuration for services in *this* file
    _defaults:
        # automatically injects dependencies in your services
        autowire: true
        # automatically registers your services as commands, event subscribers, etc.
        autoconfigure: true
        # this means you cannot fetch services directly from the container via $container->get()
        # if you need to do this, you can override this setting on individual services
        public: false

    # this creates a service per class whose id is the fully-qualified class name
    PlotlyBundle\Twig\:
        resource: '../../../../src/PlotlyBundle/Twig/*'
        tags:
            - { name: twig.runtime }

Symfony文档(Creating Lazy-Loaded Twig Extensions)上的示例需要更新,以提及启用自动连接必须(如autoconfigure Option中所述)以便工作的例子。

我向Symfony docs提交了PR