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.
Trending in Questions
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
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
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
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
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
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
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
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
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
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
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
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 9- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
sodapopcan
Ya, Tailwind won’t work with dynamic classes that way unless you list out all of the possibilities somewhere. From the docs:
So it does not see the literal strings
bg-#{@color}-900andcol-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
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
arcanemachine
You can declare them in the
safelistsection of your Tailwind config file (default:assets/tailwind.config.js). For example:EDIT: After thinking about it and RTFD, it turns out you can use regex as well:
StephanLehmke
Ok, that seems doable.
I’ll try it out, thanks!
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,textand 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.
(I didn’t try out that code but it’s the general idea)
StephanLehmke
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
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
ie, last resort
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
Just an update for the post-1.8 world, in
assets/css/app.cssafter thetailwindcssis imported: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 thevariantsmap inCoreComponents.buttonwhich means they’re automagically picked up by the CSS build without having to add a@sourceline for them.