【问题标题】:Translating Drupal 8 Custom Route Paths with Parameters使用参数翻译 Drupal 8 自定义路由路径
【发布时间】:2019-11-12 03:43:06
【问题描述】:

我有以下路线

my_module.order_details:
    path: '/account/orders/{orderId}'

在 Drupal 8 中有什么方法可以让我翻译这个路由路径一次吗?

对于所有其他路线,我一直在用我需要翻译的语言添加一个 url 别名。但是,因为它的参数 {orderId} 似乎不起作用,我不能找到一种将通配符添加到 url 别名中的方法。(我认为这可以解决我的问题)

我知道我可能会为每个 orderId 创建一个翻译后的 url 别名,但如果可能的话,我想避免这种情况。

谢谢

【问题讨论】:

    标签: routing drupal-8 translate


    【解决方案1】:

    动态路由转换示例:

    your_module.routing.yml

    route_callbacks:
      - '\Drupal\your_module\DynamicRoutes\DynamicRoutes::routes'
    

    your_module/src/DynamicRoutes/DynamicRoutes.php

    <?php
    
    namespace Drupal\your_module\DynamicRoutes;
    
    use Symfony\Component\Routing\Route;
    use Symfony\Component\Routing\RouteCollection;
    
    
    /**
     * Listens to the dynamic trousers route events.
     */
    class DynamicRoutes {
    
      public function routes(){
        $route_collection = new RouteCollection();
    
    
        $route_lang_en = new Route(
          // path
          '/example-lang-en',
          // defaults
          [
            // example controller
            '_controller' => '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage',
            '_title' => 'Your title en'
          ],
          // requirements:
          [
            '_permission' => 'access content',
          ]
        );
        $route_collection->add('example.language_en', $route_lang_en);
    
        $route_lang_fr = new Route(
          '/example-lang-fr',
          [
            '_controller' => '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage',
            '_title' => 'Your title fr'
          ],
          ['_permission' => 'access content']
        );
        $route_collection->add('example.language_fr', $route_lang_fr);
    
        return $route_collection;
      }
    }
    

    这个函数等价于:

    example.language_en:
      path: '/example-lang-en'
      defaults:
        _controller => '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage',
        _title => 'Your title en'
      requirements:
        _permission: 'access content'
    
    example.language_fr:
      path: '/example-lang-fr'
      defaults:
        _controller => '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage',
        _title => 'Your title fr'
      requirements:
        _permission: 'access content'
    

    以上代码仅用于说明。但是,我建议使用一些自定义可重用方法来构建路由,该方法可以遍历所有语言,并为path_title 提供自定义翻译,而_controller'_permission' 和任何其他不可翻译的数据在每个路由翻译中被重用。

    对于调试路由drupal console很有用

    drupal dr(列出所有路由)

    drupal dr example.language_en(获取示例路由参数)

    drupal dr example.language_fr(获取示例路由参数)

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2015-08-08
      • 2016-12-29
      • 2016-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多