Coder Social home page Coder Social logo

Comments (5)

weierophinney avatar weierophinney commented on July 19, 2024

Well you have to pass locale variable to twig in middleware


Originally posted by @vaclavvanik at zendframework/zend-expressive#524 (comment)

from mezzio.

weierophinney avatar weierophinney commented on July 19, 2024

My Twig extension loads translator, but it needs the locale information. So how can I pass the locale from middleware to Twig extension or how can I get it in the extension?


Originally posted by @back-2-95 at zendframework/zend-expressive#524 (comment)

from mezzio.

weierophinney avatar weierophinney commented on July 19, 2024

Inject the translator extension into the locale detection middleware.
Update the locale after detection into the extension.


Originally posted by @geerteltink at zendframework/zend-expressive#524 (comment)

from mezzio.

weierophinney avatar weierophinney commented on July 19, 2024

I created static method in the Extension class and I set locale in Localization middleware after detection.


Originally posted by @back-2-95 at zendframework/zend-expressive#524 (comment)

from mezzio.

weierophinney avatar weierophinney commented on July 19, 2024

Actually, you don't need to inject the locale into the extension. You can set the default locale directly in the translator. Here is how I did it a while back (old code):

<?php
declare(strict_types = 1);

namespace App\Middleware\I18n;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Symfony\Component\Translation\TranslatorInterface;
use Zend\Diactoros\Response\RedirectResponse;
use Zend\Stratigility\MiddlewareInterface;

class LocalizationMiddleware implements MiddlewareInterface
{
    private $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    public function __invoke(Request $request, Response $response, callable $out = null) : Response
    {
        $acceptedLanguages = ['en', 'nl', 'fr', 'de', 'es'];
        $locale = $request->getAttribute('locale');

        // If there is no or an invalid locale
        if (!$locale || !in_array(substr(trim($locale), 0, 2), $acceptedLanguages, true)) {
            // Try the user preferred locales
            $userLocales = $request->getServerParams()['HTTP_ACCEPT_LANGUAGE'] ?? '';
            foreach (explode(',', $userLocales) as $userLocale) {
                if (in_array(substr(trim($userLocale), 0, 2), $acceptedLanguages, true)) {
                    $locale = $userLocale;
                    break;
                }
            }
        }

        // Fallback to first accepted language
        if (!$locale) {
            $locale = $acceptedLanguages[0];
        }

        // Only the language is needed
        $locale = substr(trim($locale), 0, 2);

        if ($request->getUri()->getPath() === '/') {
            // Redirect and set the locale for the homepage
            return new RedirectResponse('/' . $locale);
        }

        // Set current locale
        $this->translator->setLocale($locale);

        // Get response first, apply content language later
        if (null !== $out) {
            $response = $out($request->withAttribute('locale', $locale), $response);
        }

        // Append the preferred language if it's different from the locale
        if ($acceptedLanguages[0] !== $locale) {
            $locale .= ', ' . $acceptedLanguages[0];
        }

        // Add the content language to the response
        return $response->withHeader('Content-Language', $locale);
    }
}

Originally posted by @geerteltink at zendframework/zend-expressive#524 (comment)

from mezzio.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.