【问题标题】:Symfony not loading runtime Twig extensionSymfony 未加载运行时 Twig 扩展
【发布时间】:2018-11-06 08:33:30
【问题描述】:

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

输入:src/PlotlyBundle/Twig/AppRuntime.php

<?php
namespace PlotlyBundle\Twig;

class AppRuntime
{
    public function __construct()
    {
    }

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

输入:src/PlotlyBundle/Resources/config/services.yml

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

输入: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')
            ),
        ];
    }
}

输入:src/AppBundle/Controller/DashboardController.php

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

输入:app/Resources/views/dashboard/index.html.twig

{{ bi_draw() }}

【问题讨论】:

  • 感觉不对。文档是不是错了?你可以试试class: PlotlyBundle\Twig\AppExtension吗?
  • ^ 不,没有错——你是自动接线的吗?否则你需要用twig.extension 标记它
  • 我已经尝试过:使用 xdebug 时,我看到构造函数被调用但 getFunctions 未被调用。我应该向我的包(PlotlyBundle)添加依赖注入吗?
  • 我在service.yml中添加了标签
  • 你能用它更新你的帖子吗?您的服务容器的自动配置选项是否已启用? (symfony.com/doc/3.4/…)

标签: php symfony twig


【解决方案1】:

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

输入: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 文档提交了 PR

【讨论】:

  • Twig 子命名空间的所有服务标记为twig.runtime 不是正确的解决方案。这些服务中的大多数不是运行时,而是扩展。它解决您的问题的原因是您现在正在将扩展程序注册为服务(并且由于自动配置而被标记为扩展程序),这在您的原始配置中没有完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
  • 2018-12-13
相关资源
最近更新 更多