Checking if user is authenticated in Phoenix templates

986 Views Asked by At

I am working on a phoenix application. The authentication part is implemented with Guardian.

Like a typical web site, the app has a header, footer, and a sidebar. These are static pages in the layout folder.

tree view -lib |--admin_app_web |--templates |--layouts |--app.html.eex |--header.html.eex |--sidebar.html.eex |--main.html.eex

The app.html.eex looks something like this

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
  </head>

  <body>
    <%= render "header.html", conn: @conn%>
    <%= render "flash.html", conn: @conn%>
    <%= render "main.html", assigns %>
    <%=# render "footer.html" %>
      <script src="<%= static_path(@conn, "/js/app.js") %>"></script>
      <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
      <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
  </body>
</html>

main.html.eex is on these lines

<main role="main" class="row my-3">
  <div class="col-2">
    <%= render "sidebar.html" %>
  </div>
  <div class="col">
    <%= render @view_module, @view_template, assigns %>
  </div>
</main>

I want to render the sidebar.html.eex only if user is authenticated, how to achieve this?

1

There are 1 best solutions below

1
On BEST ANSWER

You can check if a user is authenticated using Guardian.Plug.authenticated?/2 and use if to selectively render the sidebar template.

<div class="col-2">
  <%= if Guardian.Plug.authenticated?(@conn, []), do: render("sidebar.html") %>
</div>