Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing Zend Framework 2 Language in url

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%',
                        ),
                    ),
                ),
            ),
        ),
    ),
like image 456
directory Avatar asked May 22 '13 12:05

directory


1 Answers

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)?',
                        ),
                    ),
                ),
            ),
        ),
    ),
),
like image 114
Crisp Avatar answered Nov 06 '22 23:11

Crisp