无法自动装配方法“__construct()”的服务参数“$locales”是类型提示 "string",您应该在 symfony 中显式配置它的值

Cannot autowire service argument "$locales" of method "__construct()" is type-hinted "string", you should configure its value explicitly in symfony

我想使用新的 md2html Twig 过滤器轻松转换 Markdown 但遇到此错误:

" Cannot autowire service "App\Twig\AppExtension": argument "$locales" of method "__construct()" is type-hinted "string", you should configure its value explicitly. "

如何解决这个错误?

代码:

// src/Twig/AppExtension.php

namespace App\Twig;

use App\Utils\Markdown;
use Symfony\Component\Intl\Locales;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;


/**
 * This Twig extension adds a new 'md2html' filter to easily transform Markdown
 * contents into HTML contents inside Twig templates.
 *
 */
class AppExtension extends AbstractExtension
{
    private $parser;
    private $localeCodes;
    private $locales;

    public function __construct(Markdown $parser, string $locales) // Error this line...
    {
        $this->parser = $parser;

        $localeCodes = explode('|', $locales);
        sort($localeCodes);
        $this->localeCodes = $localeCodes;
    }

    /**
     * {@inheritdoc}
     */
    public function getFilters(): array
    {
        return [
            new TwigFilter('md2html', [$this, 'markdownToHtml'], ['is_safe' => ['html']]),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions(): array
    {
        return [
            new TwigFunction('locales', [$this, 'getLocales']),
        ];
    }

    /**
     * Transforms the given Markdown content into HTML content.
     */
    public function markdownToHtml(string $content): string
    {
        return $this->parser->toHtml($content);
    }

    /**
     * Takes the list of codes of the locales (languages) enabled in the
     * application and returns an array with the name of each locale written
     * in its own language (e.g. English, Français, Español, etc.).
     */
    public function getLocales(): array
    {
        if (null !== $this->locales) {
            return $this->locales;
        }

        $this->locales = [];
        foreach ($this->localeCodes as $localeCode) {
            $this->locales[] = ['code' => $localeCode, 'name' => Locales::getName($localeCode, $localeCode)];
        }

        return $this->locales;
    }
}

Symfony 要求您手动 define service's string parameters.

以下配置应该对您有所帮助:

#config/services.yaml
services:
    App\Twig\AppExtension:
        arguments:
            $locales: 'en|de'