Best way to add class to an element based on some condition?

Hi,

I have a query which lists user projects and those project can have different statuses. Some can be active, some can be pending, etc… When I list them in my template, I want them to have different background colors, so I want active project to have bg-green-300class and all other projects to have bg-gray-300 class.

How do I add those classes depending on the project status? (I’m not using LiveView)

Method 1

<%= if project.status == "active" do %>
    <div class="bg-green-300"><%= project.status %></div>
<% else %>
    <div class="bg-gray-300"><%= project.status %></div>
<% end %>

Method 2 with helper function

# helper
def add_classes_to_project(project) do
    if project.status == "active", do: "bg-green-300", else: "bg-gray-300"
end

# template
<div class={"#{ProjectHelper.add_classes_to_project(project)}"}><%= project.status %></div>

Which approach is better or is there some other, better way to do it?

I would choose method 2, but with modifications.

def add_classes_to_project(%{status: "active"}), do: "bg-green-300"
def add_classes_to_project(_project), do: "bg-gray-300"

No need to wrap inside “”, You can use the function directly, and I would import the helper, so I could write…

<div class={add_classes_to_project(project)}><%= project.status %></div>
2 Likes

I still use Conditional css class names - #4 by Dabsy

Can build neat class lists like

class={[
  "base-classes",
  classes("text-lg p-4": @size == :lg, "foo": @size == :medium),
  @class
]}

For your example case

class={["bg-gray-300", classes(" bg-green-300": @active)]}
2 Likes

Great, thanks a lot for this solution.