#Tailwind in Astro map function.
1 messages · Page 1 of 1 (latest)
A code sample of what you're trying to do would be nice.
From #general you had:
{
pricing.data.map(p => (
<div class="border-${p.theme}-500">
...
</div>
))
}
You can't use variables to construct class names with Tailwind. Tailwind goes through your class attributes and generates the CSS based on the class names it finds. From Tailwind's point of view, border-${p.theme}-500 is not a class name it recognizes.
What you could do in this particular case, is add your own custom colors to Tailwind, then you can just have border-theme-500
https://tailwindcss.com/docs/customizing-colors#adding-additional-colors
The colour has already been added. The problem is the dynamic generation. Theoretically, it should be possible — but provided Astro generates the HTML before Tailwind picks up on it.
Right now it seems like there's more of a static analysis of the input files.
It's not possible. It's in the Tailwind CSS docs:
https://tailwindcss.com/docs/content-configuration#dynamic-class-names
Oh well, too bad then.
All you have to do is move the code into the frontmatter:
---
...
const bgColor = `border-${p.theme}-500`
---
{
pricing.data.map(p => (
<div class:list={["text-bold", {bgColor}]}>
...
</div>
))
}
Note: not tested
Tested, doesn't work unfortunately.
There's an alternate way to make them work — that's to create classes around that use these variables.
So in the example below, if border-green-500 exists somewhere else, the class will be generated and it will work.
<div class="border-green-500"> Elsewhere... </div>
{
pricing.data.map(p => (
<div class="border-${p.theme}-500">
...
</div>
))
}
If you're going with that approach, then that's what safelist is for, but it can also bloat your CSS, so use it with caution.
https://tailwindcss.com/docs/content-configuration#safelisting-classes