StephanLehmke

StephanLehmke

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.

Showing Posts 1 to 9

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.

StephanLehmke

StephanLehmke OP

Huh. That’s inconvenient, because it much diminishes the usefulness of components.
I’m loath to put explicit styling in my HEEX templates, so I had hoped to use the components for this kind of dynamic HTML processing.

So it seems the best way would be define a specific component for each variant, duplicating the HEEX code every time…
i.e. <.button_red>, <button_blue>, …

And I can’t even abstract all those from a single general button function inside the component, because I have to completely write out the HEEX so it can be scanned.

ergh :frowning:

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 OP

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)

StephanLehmke

StephanLehmke OP

Of course, in the end the naming needs to be based on purpose; that just was the first thing to try out.

The col-span thing is probably a better example, because I plan to use a grid with 12 columns so I can switch between 2, 3, 4 column mode as needed.

The idea of doing abstraction by calling functions from within the HEEX sigil instead of calling a function that tries to generate classes dynamically via string comprehension makes a lot of sense.

In the end it’s probably not that much of a hardship because indeed, the notation should be tailored to the intended use, which won’t leave too many valid use cases for dynamically generated class names.

I just was appalled by the prospect of littering my HEEX templates with explicit <div class="... because it was somehow impossible to abstract away without enormous effort.

arcanemachine

arcanemachine

To be fair, I think the term ‘last resort’ may be a bit dramatic, as I was previously creating templates with the required classes in them just so they would be included, which I think is far more clunky than just safelisting.

But I took another look at the docs, and you can use regex to prevent unnecessary repitition, so I edited my post with an example that decreases the, ahem, verbosity of my intial suggestion.

Definitely should be avoided if possible, but the option exists for a reason.

sodapopcan

sodapopcan

ie, last resort :wink: I certainly wasn’t implying it’s a useless option, but “last resort” to me just means you can’t think of any other way. There are certainly other ways here as requiring different pre-defined styled buttons is very common usecase. Of course if you want to go the route of just defining dynamic classes, you can. I think there is a JS lib that allows you to do this now? I can’t remember what it’s called, just saw something on YouTube recently but I generally don’t keep up with that world. I’m just personally not a fan as it feels a little brittle to be directly manipulating TW classes from the outside but it’s not the worst thing in the world. It sure makes changing the colour later on a bit of a hassel, though.

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.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
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
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
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
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews