1

I moved some code to app.html.eex from post/index.html.eex

  <%= if @user do %>
        <ul class="nav navbar-nav navbar-right">
          <li>Hello <%= @user.username %>!</li>
          </ul>
           <ul class="nav navbar-nav navbar-right">
   <li> <%= link "logout", to: session_path(@conn, :logout), method: :delete, class: "logout-button" %></li>
      </ul>
      </ul>
        <% else %>
              <ul class="nav navbar-nav navbar-right">
      <li ><a class="login" href="/users/signin">Login</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
      <li><a class="signup" href="/users/new">Signup</a></li>
      </ul>
      <% end %>

When a user tries to log on, it raises:

assign @user not available in eex template.
Please make sure all proper assigns have been set. If this
is a child template, ensure assigns are given explicitly by
the parent template as they are not automatically forwarded.
Available assigns: [:conn, :view_module, :view_template]

Here is part of the code from user controller:

def index(conn, _params) do
    users = Auths.list_users()
    render(conn, "index.html", users: users)
  end

  def new(conn, _params) do
    changeset = Auths.change_user(%Citybuilder.Auths.User{})
    render(conn, "new.html", changeset: changeset)
  end

  def create(conn, %{"user" => user_params}) do
    case Auths.create_user(user_params) do
      {:ok, user} ->
        conn
        |> put_flash(:info, "Welcome! Happy writing :)")
        |> redirect(to: "/users/signin")
      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

  def signin(conn, _params) do
    render(conn, "signin.html")
  end

I'm unsure how to specifically reference app.html.eex from the controller.

I looked at similar questions but could not find an answer:

assign @changeset not available in eex template

I need to add assigns after "signin.html.eex", following the conn, template, assigns pattern.

def signin(conn, _params) do
    render(conn, "signin.html")
  end
RubyRube
  • 602
  • 5
  • 24

1 Answers1

1

By <%= if @user %>, I'm assuming you want to test if this variable is assigned by the controller or not. In that case, you can't use the @ syntax as it raises an error if the variable is not set. You can instead use the assigns map (the map that contains all the bindings) with bracket access syntax.

Change:

<%= if @user do %>

To:

<%= if user = assigns[:user] do %>

And then, in the code inside the if, change all @user to just user.

Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • Thanks, that works. To clarify; The code block checks if the user is logged on. If they are, it prints a welcome message, and logout button in the navbar. If there is no logon, it offers only login and signup. – RubyRube Oct 09 '17 at 17:11