Conditional css class names

How to set conditional class names in a template. Looking at the code below I’m wanting to toggle between bg-gray-900 and bg-gray-300 depending if the page is the active page. ie. `@page = “settings”?

<%= link "Account Settings", to: Routes.user_settings_path(@conn, :edit), class: "px-3 py-2 text-sm font-medium text-white bg-gray-900 rounded-md" %>

Those could help

You just need to change the “active” class name to be the color you want and the nil or default value to be the other shade.

2 Likes

I ended up using this inline conditional for applying the class, works for my use case and I feel it keeps it simple. Just set a ‘page’ variable on the render/3 in the controller.

<%= link "Account Settings", to: Routes.user_settings_path(@conn, :edit), class: "#{if @page === "account_settings", do: "bg-gray-900 "}px-3 py-2 text-sm font-medium text-white bg-gray-900 rounded-md" %>

I pinched this snippet from a previous dev working on my current project.

  def classes(classes) do
    classes
    |> Enum.filter(&elem(&1, 1))
    |> Enum.map(&elem(&1, 0))
    |> Enum.join(" ")
  end

Using it as

<%= some_tag "example", class: classes("is-selected": is_selected_or_something()) %>
<div class="<%= classes("is-selected": true) %>">
3 Likes