frankdejonge/symfony-i18n-routing

此包已被 废弃 并不再维护。作者建议使用 symfony/routing 包。

Symfony 4 的国际化路由

0.0.7 2018-02-06 13:35 UTC

This package is auto-updated.

Last update: 2022-02-01 13:12:08 UTC


README

此捆绑包提供 Symfony 4 的国际化路由。

Author Build Status Coverage Status Software License Packagist Version Total Downloads

目的

此捆绑包提供了一种对路由定义进行国际化的方法。这意味着您可以按区域定义路径,同时它们仍然可以路由到相同的控制器操作。

安装

composer req frankdejonge/symfony-i18n-routing

bundles.php 中注册捆绑包

<?php

return [
    FrankDeJonge\SymfonyI18nRouting\I18nRoutingBundle::class => ['all' => true],
    // ...
];

注意,如果您想使用注释,则需要确保在 FrameworkBundle 之前加载此捆绑包。

配置

frankdejonge_i18n_routing:
    default_locale: en
    use_annotations: false # set to true to enable annotation loading

Yaml 使用

从主 config/routes.yml 导入本地化路由

i18n_routes:
    resource: ./i18n_routes/routes.yml
    type: i18n_routes

现在您可以在 config/i18n_routes/routes.yml 中定义国际化路由

contact:
    controller: ContactController::formAction
    locales:
        en: /send-us-an-email
        nl: /stuur-ons-een-email

这实际上与定义相同

contact.en:
    controller: ContactController::formAction
    path: /send-us-an-email
    defaults:
        _locale: en

contact.nl:
    controller: ContactController::formAction
    path: /stuur-ons-een-email
    defaults:
        _locale: nl

如您所见,这可以节省您一些打字,并防止您需要保持两个定义同步(更不容易出错)。

注释使用

注释加载器支持常规路由注释和本地化注释。可以随意混合使用 @I18nROute@Route 注释。

<?php

use FrankDeJonge\SymfonyI18nRouting\Routing\Annotation\I18nRoute;

class ContactController
{
    /**
     * @I18nRoute({"en": "/send-us-an-email", "nl": "/stuur-ons-een-email"}, name="contact") 
     */
    public function formAction()
    {
        
    }
}

/** 
 * @Route("/prefix") 
 */
class PrefixedContactController
{
    /**
     * @I18nRoute({"en": "/send-us-an-email", "nl": "/stuur-ons-een-email"}, name="prefix_contact") 
     */
    public function formAction()
    {
        
    }
}

生成路由

可以使用指定的路由名称来生成路由。

<?php
/** @var UrlGeneratorInterface $urlGenerator */
$urlWithCurrentLocale = $urlGenerator->generate('contact');
$urlWithSpecifiedLocale = $urlGenerator->generate('contact', ['_locale' => 'nl']);