将代码从index.html.eex移动到app.html.eex后:在eex模板中分配@user不可用

时间:2017-10-09 17:00:31

标签: elixir phoenix-framework

我从post / index.html.eex

移动了一些代码到app.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 %>

当用户尝试登录时,会引发:

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]

以下是用户控制器代码的一部分:

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

我不确定如何从控制器中专门引用app.html.eex。

我看了类似的问题,但找不到答案:

assign @changeset not available in eex template

我需要按照conn, template, assigns模式在“signin.html.eex”之后添加分配。

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

1 个答案:

答案 0 :(得分:1)

<%= if @user %>,我假设您要测试控制器是否分配了此变量。在这种情况下,如果未设置变量,则无法使用@语法,因为它会引发错误。您可以使用括号访问语法来使用assigns映射(包含所有绑定的映射)。

变化:

<%= if @user do %>

要:

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

然后,在if内的代码中,将所有@user更改为user