在使用 Magento 2 GraphQl 时,字符串翻译似乎不起作用

Tob*_*ann 1 translation magento2 graphql magento-2.3

在 GraphQl Resolver 中,我们希望使用__()方法返回翻译后的字符串。不幸的是,这似乎不起作用。我们还进行了一些调试,但无法弄清楚为什么这不起作用。我的猜测是,解析器无法翻译,因为他们不知道翻译成哪种语言。但是我不知道如何设置语言。

有没有其他人遇到过这种问题,这在 PWA Studio 中是如何工作的?

小智 5

我遇到了同样的问题。我正在构建一些模块来使用 GraphQl,但我遇到了这个问题。经过大量搜索并没有发现任何东西,我调试了Magento核心以找到问题。

Magento 2 适用于多个区域,就像您在 vendor/magento/framework/App/Area.php 中看到的那样

const AREA_GLOBAL = 'global';
const AREA_FRONTEND = 'frontend';
const AREA_ADMINHTML = 'adminhtml';
const AREA_DOC = 'doc';
const AREA_CRONTAB = 'crontab';
const AREA_WEBAPI_REST = 'webapi_rest';
const AREA_WEBAPI_SOAP = 'webapi_soap';
const AREA_GRAPHQL = 'graphql';
Run Code Online (Sandbox Code Playgroud)

我调试了前端区域并在文件 vendor/magento/framework/View/DesignLoader.php 中找到了这个

public function load()
{
    $area = $this->_areaList->getArea($this->appState->getAreaCode());
    $area->load(\Magento\Framework\App\Area::PART_DESIGN);
    $area->load(\Magento\Framework\App\Area::PART_TRANSLATE);
    $area->detectDesign($this->_request);
}
Run Code Online (Sandbox Code Playgroud)

为了解决我的问题,我创建了一个插件来在 GraphQl 区域加载翻译。

脚步:

1.在app/code/Vendor/Module/etc/graphql下创建di.xml文件:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\GraphQl\Controller\GraphQl">
        <plugin name="graphql_load_translate" type="Vendor\Module\Plugin\Controller\GraphQlPlugin" sortOrder="1" disabled="false"/>
    </type>
</config>
Run Code Online (Sandbox Code Playgroud)

2. 在 app/code/Vendor/Module/Plugin/Controller/GraphQlPlugin.php 下创建你的插件类

    <?php

    namespace Vendor\Module\Plugin\Controller;

    class GraphQlPlugin
    {
        /** @var \Magento\Framework\App\AreaList $areaList */
        private $areaList;

        /** @var \Magento\Framework\App\State $appState */
        private $appState;

        public function __construct(
            \Magento\Framework\App\AreaList $areaList,
            \Magento\Framework\App\State $appState
        )
        {
            $this->areaList = $areaList;
            $this->appState = $appState;
        }

        public function beforeDispatch(\Magento\GraphQl\Controller\GraphQl $subject)
        {
            $area = $this->areaList->getArea($this->appState->getAreaCode());
            $area->load(\Magento\Framework\App\Area::PART_TRANSLATE);
        }
    }
Run Code Online (Sandbox Code Playgroud)

3. 编译类

php bin/magento setup:di:compile
Run Code Online (Sandbox Code Playgroud)

这对我有用。