Use the same liveview with different routes


Originally, I had the following routes before Live View:

    get "/tasks/closed", TaskController, :closed
    resources "/tasks", TaskController

Which worked great - in TaskController.Index I show open Tasks. In TaskController.Closed I show closed Tasks.

However, then I tried the following routes for Live View:

    live "/tasks", TaskLive.Index
    live "/tasks/closed", TaskLive.Index

Which works, but is there’s a couple of problems:

  • In TaskLive.Index.mount there’s no obvious way to tell which route was chosen
  • There isn’t an easy way to reference which particular version I’m after in a call to live_path

I did manage to address these issues by doing the following:

    live "/tasks", TaskLive.Index
    live "/tasks/closed", TaskLive.Index, session: [:closed], as: :closed

In the session parameter, :closed is fake - but I can see if session.closed exists in TaskLive.Index.mount. The as parameter means that I can do one of the following:

live_path( socket, TaskLive.Index ) # Returns "/tasks"
closed_path( socket, TaskLive.Index ) # Returns "/tasks/closed"

All of this is a bit hacky. Is there a better way to do this with live routes?