I am using LiveView and I use the push_patch
function to update the current view.
I want to encode the query params of the path I pass to push_patch
like the following:
~p"/home?list[]=a&list[]=b"
When handling the parameters on the handle_params
function, it successfully parses the previous format to a List.
The problem is that the ~p
sigil encodes this:
~p"/home?list[]=a&list[]b"
to this:
/home?list%5B%5D%3Da&list%5B%5D%3Db
Then when the handle_params
function is called it is not able to parse the list
param as a list anymore.
I hope I haven’t been too confusing, I would appreciate some help to understand how can I build a path to pass to push_patch
with the correct encoding since the ~p sigil doesn’t seem to work
Are those code examples the literal code you have or are there variables involved?
I’m pretty sure that you’re supposed to do ~p"/home?#{%{list: ["a", "b"]}}"
and let Phoenix handle the encoding.
2 Likes
Sorry I actually misswrote the way I use the ~p
sigil. I was actually doing this:
~p"/home?${encode_list(list)}"
def encode_list(list), do: list |> Enum.map(& "list[]=${&1}") |> Enum.join("&")
This would pass the query params as a string to the ~p
sigil and then it would encode the []=
characters as %5B%5D%3D
But to answer the question, that is not actual code but just a reproduction of what I have
That’s it! This solves my problem, thank you so much!
By passing that to the ~p
sigil I get a correct encoded path
I can’t find any reference to encoding lists in a path in this documentation: Phoenix.VerifiedRoutes — Phoenix v1.7.11
It would be useful to add an example for it
Search for “Query strings are also supported in verified routes”. There are two examples in there.
Oh yes but I couldn’t understand how would it encode lists, and I tried to look for the Param protocol implementation for lists but couldn’t find it either
The Phoenix.Param
protocol is for turning data (mostly structs) into path segments. That’s unrelated to query parameters. They’re encoded using: Plug.Conn.Query — Plug v1.15.3
1 Like
Oh that’s it! Thank you that’s very helpful!
Yeah I think the ~p
docs could definitely use more examples. If you know what you’re looking for you can dig into some of the related links and figure it out but it seems like a good place to make it obvious!
3 Likes