I am new to Phoenix, coming from RoR. It seems like the views are akin to Rails helpers and the likely place to put helper functions.
If that is true, how do we access the connection or the connection's assigns from within the view?
Here's my example problem.
The app displays a list of all the users. But I only want to show the API token for the user that is currently signed in. So I'm thinking a method in the UserView
is appropriate for doing something like this in the template:
<b><%= first_name(@user) %></b> (api_token: <%= display_token(@user) %>)
For the helper method in the view, I need to be able to do something like this:
def display_token(user) do
case conn.assigns.current_user do
user -> user.api_token
nil -> ""
_ -> "hidden"
end
end
Any insights are appreciated.
There's no state passed to functions in the view automatically in Phoenix. You'll have to pass @conn
in yourself as an argument to display_token
.
Template:
<b><%= first_name(@user) %></b> (api_token: <%= display_token(@conn, @user) %>)
View:
def display_token(conn, user) do
case conn.assigns.current_user do
^user -> user.api_token
nil -> ""
_ -> "hidden"
end
end
(You'll also need to use the pin operator to match current_user
against the user
passed as argument. I've fixed that in the code above.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With