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 Switch mode

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)

Last Post!

smathy

smathy

Just an update for the post-1.8 world, in assets/css/app.css after the tailwindcss is imported:

@source inline("bg-{zinc,red,blue,yellow}-{800,900}");

BUT, “the right way”™ is to use the variants, which you’d color with a Daisy theme or override yourself in assets/css/app.css, and then which you’d add explicitly into the variants map in CoreComponents.button which means they’re automagically picked up by the CSS build without having to add a @source line for them.

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement