Routing Zend Framework 2 Language in url

2019-04-09 07:20发布

问题:

For my application translation I would like to use a language structure e.g.:

  • site.com (english)
  • site.com/de/ (german)
  • site.com/fr/ (france)
  • site.com/nl/ (dutch)

etc..

I can do this easily with the router option in Literal as '[a-z]{2}' but I want to exclude languages I do not support, e.g. site.com/it/ if it is not supported I want a 404. I tried to fix this with regex (adding supported languages) but something (I do not know) went wrong.

Thanks in advance!

'router' => array(
        'routes' => array(
            'home' => array(
                'type' => 'Literal',
                'options' => array(
                    'route'    => '/',
                    'defaults' => array(
                        'controller' => 'Application\Controller\Index',
                        'action'     => 'index',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    'language' => array(
                        'type'    => 'Regex',
                        'options' => array(
                            'regex'    => '/(?<lang>(de|fr|nl))?',
                            'defaults' => array(
                                'lang' => 'en', //default
                            ),
                            'spec' => '/%lang%',
                        ),
                    ),
                ),
            ),
        ),
    ),

回答1:

I think your regex needs to be

'regex'    => '/(?<lang>(de|fr|nl)?)'

You could so the same with a Segment route and an appropriate constraint...

'router' => array(
    'routes' => array(
        'home' => array(
            'type' => 'Literal',
            'options' => array(
                'route'    => '/',
                'defaults' => array(
                    'controller' => 'Application\Controller\Index',
                    'action'     => 'index',
                ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
                'language' => array(
                    'type'    => 'Segment',
                    'options' => array(
                        'route' => '[/:lang]',
                        'defaults' => array(
                            'lang' => 'en', //default
                        ),
                        'constraints' => array(
                            'lang' => '(en|de|fr|nl)?',
                        ),
                    ),
                ),
            ),
        ),
    ),
),