Created
December 26, 2021 22:28
-
-
Save lovebes/8a0fb00ee440d41360665b1c3ddbe642 to your computer and use it in GitHub Desktop.
How to make Active Link Phoenix Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule ActiveLinkWeb.Components.ActiveLinkView do | |
use Phoenix.Component | |
import Phoenix.Controller, only: [current_path: 1] | |
def active_link(assigns) do | |
%{conn: conn, href: href} = assigns | |
link_name = | |
case href |> String.split("/") do | |
["", ""] -> "home" | |
["", rest] -> rest | |
["" | tail] -> List.last(tail) | |
end | |
style = | |
if is_active_link?(conn, href), | |
do: "font-weight: bold; font-size: 10rem;", | |
else: "font-weight: normal; font-size: 1rem;" | |
~H""" | |
<a href={@href} style={style}><%= link_name %><%= @socket %></a> | |
""" | |
end | |
defp is_active_link?(conn, href) do | |
current_path(conn) == href | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<main class="container"> | |
<p class="alert alert-info" role="alert"><%= get_flash(@conn, :info) %></p> | |
<p class="alert alert-danger" role="alert"><%= get_flash(@conn, :error) %></p> | |
<ActiveLinkWeb.Components.ActiveLinkView.active_link conn={@conn} href="/" /> / | |
<ActiveLinkWeb.Components.ActiveLinkView.active_link conn={@conn} href="/route1" /> / | |
<ActiveLinkWeb.Components.ActiveLinkView.active_link conn={@conn} href="/route1/route2" /> | |
<%= @inner_content %> | |
</main> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule ActiveLinkWeb.PageController do | |
use ActiveLinkWeb, :controller | |
def index(conn, _params) do | |
render(conn, "index.html") | |
end | |
def route1(conn, _params) do | |
render(conn, "route1.html") | |
end | |
def route2(conn, _params) do | |
render(conn, "route2.html") | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
scope "/", ActiveLinkWeb do | |
pipe_through :browser | |
get "/", PageController, :index | |
get "/route1", PageController, :route1 | |
get "/route1/route2", PageController, :route2 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment