我们如何在layout.phtml中获取本地值(即:'en'或'en_US','de'等)或Zend Framework 2中的视图?
我的本地设置与explained here
完全相同<?php
namespace FileManager;
use Zend\Mvc\ModuleRouteListener;
class Module
{
public function onBootstrap($e)
{
$translator = $e->getApplication()->getServiceManager()->get('translator');
$translator
->setLocale(\Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']))
->setFallbackLocale('en_US');
}
//...
}
我希望得到像这样的本地价值:
$locale = $this->translate()->getLocale(); // <-- It's not working anyway
我需要在调用google map api url时使用' $ locale '来获取匹配的区域设置/语言。我通过layout.phtml
中的应用程序调用它$this->headScript()->appendFile('http://maps.googleapis.com/maps/api/js?language=' . $locale);
所以我想在调用api时使语言选项动态化。
PS:我没有任何查询字符串参数,例如'language',这是一个google api,我需要在脚本url中设置(如果你不知道)请不要混淆。 未解答here
答案 0 :(得分:8)
取决于您希望从何处获取区域设置值。在任何情况下,您都可以在控制器中执行此操作,例如:
$locale = $this->request->getQuery('language');
$this->layout()->locale = $locale;
或
return new ViewModel(array('locale' => $locale));
编辑如果您只想从翻译器获取语言环境,可以在视图脚本中尝试此操作:
$this->plugin('translate')->getTranslator()->getLocale();
答案 1 :(得分:1)
我的版本就是那样
<?php
namespace FileManager;
use Zend\Mvc\ModuleRouteListener;
use Zend\Session\Container;
class Module
{
public function onBootstrap($e)
{
$application = $e->getTarget();
$serviceManager = $application->getServiceManager();
$eventManager = $application->getEventManager();
$events = $eventManager->getSharedManager();
// session container
$sessionContainer = new Container('locale');
// test if the language in session exists
if(!$sessionContainer->offsetExists('mylocale')){
// doesn't so the browser lan
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
$sessionContainer->offsetSet('mylocale', Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']));
}else{
$sessionContainer->offsetSet('mylocale', 'en_US');
}
}
// translation
$translator = $serviceManager->get('translator');
$translator ->setLocale($sessionContainer->mylocale)
->setFallbackLocale('en_US');
$mylocale = $sessionContainer->mylocale;
$events->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) use ($mylocale) {
$controller = $e->getTarget();
$controller->layout()->mylocale = $mylocale;
}, 100);
}
//...
}
布局中的
$this->headScript()->appendFile('http://maps.googleapis.com/maps/api/js?language=' . $this->mylocale);