Barbara J. Orsini
Barbara J. Orsini

Reputation: 23

How to specify a global optional segment of a scope in router.ex?

Suppose, I had a lot of different routes. Now I want to introduce an optional segment :language for a certain scope in router.ex. The result would be this:

# a small sliver of all the routes

my_site.com/fr/articles/123.html
my_site.com/es/articles/123.html
my_site.com/ru/articles/123.html

my_site.com/jj/articles/123.html # ops! should explode and 
# redirect to the default language

# if the language is missing,
# it gets the default value
my_site.com/articles/123.html 

That is, when the language parameter is missing, the default value will be used.

How to implement this?

  # something like this,
  # but this as is won't work
  scope "/language", MyAppWeb do

  end

Upvotes: 0

Views: 194

Answers (1)

JasonTrue
JasonTrue

Reputation: 19609

You can do something like this:

scope "/:language" do
  resources "/articles", ArticlesController, only: [:index, :show], as: :locale_scoped_articles
end

resources "/articles", ArticlesController

This creates two named routes, using the same controller. In this case I elected to change the route name for the scoped version of the routes (to language_scoped_articles_path, making it so that the default articles_path route helpers will not contain locale scoping. But you could do the reverse instead, depending on whether you want the "usual" route helpers to require the locale to be specified or not.

Upvotes: 1

Related Questions