StephanLehmke

StephanLehmke

Using "generated" class names in Tailwind under Phoenix 1.7+

Is there an inherent problem with dynamically generating tailwind class names in a component?

I wanted to make the button color configurable. This is mostly from the auto-generated core_components.ex. I only added the “color” attribute, so I could say something like <.button color="red">.

  attr :type, :string, default: nil
  attr :class, :string, default: nil
  attr :color, :string, default: "zinc"
  attr :rest, :global, include: ~w(disabled form name value)

  slot :inner_block, required: true

  def button(assigns) do
    ~H"""
    <button
      type={@type}
      class={[
        "phx-submit-loading:opacity-75 rounded-lg bg-#{@color}-900 hover:bg-#{@color}-800 py-2 px-3",
        "text-sm font-semibold leading-6 text-white active:text-white/80",
        @class
      ]}
      {@rest}
    >
      <%= render_slot(@inner_block) %>
    </button>
    """
  end

The HTML source of the page looks OK to me:

    <button class="phx-submit-loading:opacity-75 rounded-lg bg-red-900 hover:bg-red-800 py-2 px-3 text-sm font-semibold leading-6 text-white active:text-white/80">
  Speichern und beenden
</button>
    <button class="phx-submit-loading:opacity-75 rounded-lg bg-zinc-900 hover:bg-zinc-800 py-2 px-3 text-sm font-semibold leading-6 text-white active:text-white/80" name="Weiter">
  Speichern
</button>

But the colors don’t show up unless they are also explicitly used somewhere else.

There is essentially the same problem with my attempt to define a component for a grid column with configurable span:

  @doc """
  Renders a grid column.
  """
  attr :span, :string, default: "1"
  slot :inner_block, required: true

  def gridcol(assigns) do
    ~H"""
    <div class={"col-span-#{@span}"}>
    <%= render_slot(@inner_block) %>
    </div>
    """
  end

The col-span seems to be ignored although the HTML source looks Ok.

Marked As Solved

sodapopcan

sodapopcan

Ya, Tailwind won’t work with dynamic classes that way unless you list out all of the possibilities somewhere. From the docs:

Tailwind CSS works by scanning all of your HTML files, JavaScript components, and any other templates for class names, generating the corresponding styles and then writing them to a static CSS file.

So it does not see the literal strings bg-#{@color}-900 and col-span-#{@span} a valid class names so it ignores them.

If you want to provide custom colors I would use vanilla CSS. Another hacky solution would be to just list all possible classes in a comment, though that isn’t a great solution.

Also Liked

arcanemachine

arcanemachine

You can declare them in the safelist section of your Tailwind config file (default: assets/tailwind.config.js). For example:

module.exports = {
  content: ["./js/**/*.js", "../lib/*_web.ex", "../lib/*_web/**/*.*ex"],
  theme: {
    // ...
  },
  safelist: [
    "bg-primary",
    "bg-secondary",
    "bg-accent",
    "bg-neutral",
    "bg-info",
    "bg-success",
    "bg-warning",
    "bg-error",
  ],
  plugins: [
    // ...
  ],
};

EDIT: After thinking about it and RTFD, it turns out you can use regex as well:

  safelist: [
    "bg-(primary|secondary|accent|neutral|info|success|warning|error)","
  ]
StephanLehmke

StephanLehmke

Ok, that seems doable.
I’ll try it out, thanks!

sodapopcan

sodapopcan

That’s cool, I wasn’t aware of safelist, though it’s still just a “cleaner” solution over writing them all out in a comment—a bit unscalable if you have a lot of colors and have to cover bg, text and so on. I’m seeing the docs even say it’s a last resort. Though if you are only doing the background color and text color, it could be ok.

@StephanLehmke At first I was assuming you were talking about allowing users to provide custom colors but if you just want different colour buttons, it’s far more preferable to define them either, as you mentioned, as different components, or use an attribute. It’s probably even better to defined them based on their purpose rather than colour, but that is up to you. You shouldn’t need much duplication.

def button(%{type: :primary} = assigns) do
  assigns = assign(assigns, :class,  "text-blue-50 bg-blue-900")

  ~H"""
  <.button class={@class} />
  """
end

def button(%{type: :muted} = assigns) do
  assigns = assign(assigns, :class,  "text-zinc-700")

  ~H"""
  <.button class={@class} />
  """
end

def button(assigns) do
  assigns = assign_new(assigns, :class, fn -> "text-zinc-900 text-zinc-100" end)

  ~H"""
  <button class={@class}>
    <%= render_slot(@inner_block) %>
  </button>
  """
end

# Usage:

<.button type={:primary} />

(I didn’t try out that code but it’s the general idea)

Where Next?

Popular in Questions Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement