I've started to teach myself Phoenix Framework and their documentation is pretty good. I have however hit a stumbling block when it comes to specifying optional routing parameters. The Phoenix Framework Routing Documentation makes no mention of this as a feature, so I'm assuming the onus falls on the dev to come up with a solution.
I'll lay out my use case:
- User visits site at
/page/test
, a custom Plug then implements some code to find or assign alocale
to the connection. - Since there's no
:locale
parameter in the path, the default is used as per the line in my pipeline, which isplug HelloPhoenix.Plugs.Locale, "en"
. - User visits site at
/fr/page/test
, and the same code gets executed in the pipeline, except time as the:locale
parameter is present in the route, the custom Plug (HelloPhoenix.Plugs.Locale
).
Now from a routing perspective, if I can't specify that the :locale
parameter is optional, I end up with double the number of routes, e.g.:
scope "/", HelloPhoenix do
use_pipeline :browser
plug HelloPhoenix.Plugs.Locale, "en"
# Route without locale
get "/page/:slug", PageController, :show
# Route with locale
get "/:locale/page/:slug", PageController, :show
end
as you can tell, this could quickly become very arduous and repetitive without the ability to specify an optional routing parameter.
No I do have a workaround, which I'll post in an answer, but I'm not sure if it's (a) right, and (b) the easiest solution, since I'm new to Erlang, Elixir and Phoenix (I'm coming from a background in Ruby & PHP OOP).