zizheng
Set active Bootstrap navbar item with Phoenix
Hi all, I’m using Phoenix with Bootstrap and I’m having some trouble figuring out the best way to set the active navbar item.
In Bootstrap, adding the "active" class to a nav item sets it as the current nav item. My goal is to do something like this in my Phoenix templates:
<li class="nav-item <%= nav_item_state(:foos) %>">
<%= link "Foos", to: Routes.foo_path(@conn, :index), class: "nav-link" %>
</li>
<li class="nav-item <%= nav_item_state(:bars) %>">
<%= link "Bars", to: Routes.bar_path(@conn, :index), class: "nav-link" %>
</li>
and something like this in my controllers:
# I want to avoid having to pass `:foos`/`:bars` as an assign every time I call `render`
defmodule MyAppWeb.FooController do
...
def active_nav_item, do: :foos
end
defmodule MyAppWeb.BarController do
...
def active_nav_item, do: :bars
end
I want nav_item_state(:foos) to return "active" when the current controller is FooController, and to return "" otherwise.
I think nav_item_state should be defined in my LayoutView module, but not really sure how to piece things together. Appreciate any suggestions!
Most Liked
ehayun
You can create a function in your view file like this
def active_menu(conn, item) do
if conn.request_path =~ Atom.to_string(item), do: "active", else: ""
end
and in your html.eex file do like this
<li class=" <%= active_menu(@conn, :foo) %>"> <a href="/foo">foo</a></li>
<li class=" <%= active_menu(@conn, :bar) %>"> <a href="/bar">bar</a></li>
zizheng
Thanks, I ended up creating a custom plug that puts the current active nav item in the conn:
defmodule MyAppWeb.FooController do
plug MyAppWeb.Plugs.ActiveNavItem, :foos
...
end
and added a function in my LayoutView that queries the conn for this information.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








