7

How do you translate the path portion of a module route?

For instance you have:

module_name.my_route_name:
  path: '/path/to/content'
  defaults:
    _controller: \Drupal\module_name\Controller\MyController

How do I get /es/ruta-de-acceso/a/contenido to point to the same route name?

2 Answers 2

7

As far as I know (anyone, correct me if I'm wrong!) this is not possible in the routing system. You can however add a path alias, and make "/ruta-de-acceso/a/contenido" an alias in the Spanish language for '/path/to/content'.

Now the problem with path aliases, compared to routes, it that they are considered content, not core or configuration. As a result there is (again: AFAIK) currently no way to export them and deploy them to a server. For a recent project, I solved that with some custom code in the .install file of a custom module. You can see the code in this Github gist: Drupal 8: Custom path aliases exported to code.

3
  • 1
    Hey man, thanks for sharing. I see exactly what you're talking about and I'll definitely implement it. One thing came to mind was to actually add the translated paths to the route entry in the config file; read the config files in the install phase and then add aliases to the database. I dunno if that can work, but I'll look into it. Cheers!
    – IslandDev
    Jul 21, 2016 at 13:24
  • No problem! I agree that it would make sense to bundle the translated paths with your route definitions. If you can make that work, I'd love to see your code! Jul 21, 2016 at 13:59
  • Although path aliases can't handle parameters; so if you had a path like start/[nid] and needed the FR version to be at début/[nid]; I think you are out of luck. Sadly i don't think this is possible in D8; but possibly in D9, if it adopts Symphony 4.1. Possibly the hook_language_switch_links_alter function might help? I.e. 2 separate routes and use that to "link" them together from the language switcher.
    – liquidcms
    Jan 25, 2021 at 23:08
1

I think it's the other way around, it's the route that points to a path. Ideally you could have just one route that would be used for every language and I suppose that works with node/{id} . But when using aliases, the only way I got this working was by defining one route per language. Not pretty at all.

By the way, then in Twig I've used {{ path('module_name.my_route_name.' ~ language) }} . Also not pretty at all.

1
  • You are right about what is pointing to what.
    – IslandDev
    Mar 20, 2017 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.