Pimcore ver.5 LanguageSwitcher 言語選択

#1

言語選択にSymfonyのヘルパークラスを使用するようにします。

/app/Resources/views/Includes/language.html.php

変更前

<?php
/** @var \AppBundle\Templating\LanguageSwitcher $languageSwitcher */
$languageSwitcher = $this->app->getContainer()->get('website_demo.language_switcher');
?>

変更後

<?php
/** @var \AppBundle\Templating\Helper\LanguageSwitcher $languageSwitcher */
$languageSwitcher = $this->languageSwitcher();
?>

/src/AppBundle/Resources/config/services.yml 内のTEMPLATINGの項目を変更

変更前

#
# TEMPLATING
#

website_demo.area.brick.blockquote:
    class: AppBundle\Document\Areabrick\Blockquote
    tags:
        - { name: pimcore.area.brick, id: blockquote }

website_demo.language_switcher:
    class: AppBundle\Templating\LanguageSwitcher
    arguments: ['@Pimcore\Model\Document\Service']

変更後

#
# TEMPLATING
#

# a sample areabrick which is manually registered
AppBundle\Document\Areabrick\Blockquote:
    tags:
        - { name: pimcore.area.brick, id: blockquote }

# a sample templating helper
AppBundle\Templating\Helper\LanguageSwitcher:
    # templating helpers need to be public as they
    # are fetched from the container on demand
    public: true
    tags:
        - { name: templating.helper, alias: languageSwitcher }

/src/AppBundle/Templating/Helper/LanguageSwitcher.phpを作成します。

<?php

declare(strict_types=1);

/**
 * Pimcore
 *
 * This source file is available under two different licenses:
 * - GNU General Public License version 3 (GPLv3)
 * - Pimcore Enterprise License (PEL)
 * Full copyright and license information is available in
 * LICENSE.md which is distributed with this source code.
 *
 * @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     GPLv3 and PEL
 */

namespace AppBundle\Templating\Helper;

use Pimcore\Model\Document;
use Pimcore\Model\Document\Service;
use Pimcore\Tool;
use Symfony\Component\Templating\Helper\Helper;

class LanguageSwitcher extends Helper
{
    /**
     * @var Service|Service\Dao
     */
    private $documentService;

    public function __construct(Service $documentService)
    {
        $this->documentService = $documentService;
    }

    /**
     * @inheritDoc
     */
    public function getName()
    {
        return 'languageSwitcher';
    }

    public function getLocalizedLinks(Document $document): array
    {
        $translations = $this->documentService->getTranslations($document);

        $links = [];
        foreach (Tool::getValidLanguages() as $language) {
            $target = '/' . $language;

            if (isset($translations[$language])) {
                $localizedDocument = Document::getById($translations[$language]);
                if ($localizedDocument) {
                    $target = $localizedDocument->getFullPath();
                }
            }

            $links[$target] = \Locale::getDisplayLanguage($language);
        }

        return $links;
    }
}
0 Likes