Hello elixir community
As a pretty much newcomer to elixir, I was thinking how I could get started with some practical but straightforward work and I got the idea to build a simple css classname join utility à la https://github.com/lukeed/clsx
I don’t know if sharing code via forum is something seen in this community, but I would really love to get feedback how I can improve on my code
First and foremost I was curious to hear if there already exist some recommended, best practice helpers regarding classname handling in eex.
This is what I came up with:
defmodule KatyWeb.Css do
@var %{
:some_global => "bg-blue-500 hover:bg-blue-300"
}
def get(key) do
@var[key]
end
defp convertNameToClass(name) when is_map_key(@var, name) do
[@var[name]]
end
defp convertNameToClass(name) when is_list(name) do
Enum.flat_map(name, &convertNameToClass/1)
end
defp convertNameToClass(name) do
[name]
end
@type names :: %{any: boolean}
@spec join(names) :: String.t()
def join(names) do
names
|> Enum.filter(fn({_key, value}) -> value end)
|> Enum.map(fn({key, _value}) -> key end)
|> Enum.flat_map(&convertNameToClass/1)
|> IO.inspect
|> Enum.uniq
|> Enum.join(" ")
end
end
Usage Example: (in liveview with a little counter button):
<button
class="<%= Css.join(%{
"my-24 mx-6 p-6 text-4xl font-light tracking-tight" => 1,
"bg-green-500 hover:bg-green-300" => @count == 0,
"bg-orange-500 hover:bg-orange-300" => @count == 1,
[:some_global, "font-bold"] => @count == 2,
"bg-red-500 hover:bg-red-300" => @count > 2
}) %>"
phx-click="count"
>
Count: <%= @count %>
</button>
Demo:
Thanks a lot in advance for your feedback and time