Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to the connection or 'assigns' from within a View

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.

like image 563
Midwire Avatar asked Dec 19 '22 17:12

Midwire


1 Answers

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.)

like image 137
Dogbert Avatar answered Jan 07 '23 22:01

Dogbert