Forcing the Twig Locale

后端 未结 4 2006
一向
一向 2021-02-03 21:31

I would like to use the Twig template system to template my e-mails. The locale of the e-mail should be based on a user setting, not from the session or request locale. How can

4条回答
  •  遇见更好的自我
    2021-02-03 21:53

    Here is a solution (it works well, except sub-templates (Twig: render(controller('AppBundle:Invoice/Index:productTotalPartial')))

    translator = $translator;
        }
    
        /**
         * Change the locale
         *
         * @param string $locale
         */
        public function setLocale($locale)
        {
            $this->previousLocale = $this->translator->getLocale();
    
            $this->translator->setLocale($locale);
            $this->setPhpDefaultLocale($locale);
        }
    
        /**
         * Revert the locale
         */
        public function revertLocale()
        {
            if ($this->previousLocale === null) {
                return;
            }
    
            $this->translator->setLocale($this->previousLocale);
            $this->setPhpDefaultLocale($this->previousLocale);
    
            $this->previousLocale = null;
        }
    
        /**
         * Use temporary locale in closure function
         *
         * @param string $locale
         * @param \Closure $c
         */
        public function temporaryLocale($locale, \Closure $c)
        {
            $this->setLocale($locale);
    
            $c();
    
            $this->revertLocale();
        }
    
        /**
         * Sets the default PHP locale.
         * Copied from Symfony/Component/HttpFoundation/Request.php
         *
         * @param string $locale
         */
        private function setPhpDefaultLocale($locale)
        {
            // if either the class Locale doesn't exist, or an exception is thrown when
            // setting the default locale, the intl module is not installed, and
            // the call can be ignored:
            try {
                if (class_exists('Locale', false)) {
                    /** @noinspection PhpUndefinedClassInspection */
                    \Locale::setDefault($locale);
                }
            } catch (\Exception $e) {
            }
        }
    }
    

    Example:

    if ($this->getLocale()) {
        $this->localeSwitcher->setLocale($this->getLocale());
    }
    
    $html = $this->templating->render($templatePath);
    
    if ($this->getLocale()) {
        $this->localeSwitcher->revertLocale();
    }
    

提交回复
热议问题