timonweb / django-tailwind

Django + Tailwind CSS = 💚
https://django-tailwind.readthedocs.io
MIT License
1.45k stars 89 forks source link

Arbitrary value from template variable not being parsed by tailwind: ie - `<div class="bg-[{{product.color}}]">` #153

Closed pljspahn closed 1 year ago

pljspahn commented 2 years ago

I have a model that uses django-colorfield on a product model to save a color to the item.

I then use that value inside a loop in my template to set the background color using tailwind's arbitrary value:

{% for product in object_list %}
    <div class=bg-[{{product.color}}]">{{product.name}}</div>
{% endfor %}

The template renders with a correct value, ie:

<div class="bg-[#FFE321]">Fancy Product</div>

However, it seems that Tailwind isn't including this in its build of the stylesheet, as no color is rendered on the screen, it's just white. I've restarted manage.py and disabled browser caching, force reload, etc and it just doesn't add this.

But ... If instead of using the template variable, I simply type in the value manually into the template, then Tailwind picks this up and includes it in the build, and I can then switch it back to the template variable and it works properly.

Does this basically mean that Tailwind is parsing the template before it's been rendered, as it ends up seeing the template variable syntax, ie {{product.color}} and ignores it since it's not a valid value?

I have a couple very awkward work arounds that I can use for this (using a defined palette with django-colorfield, among other things) but this will really limit and irritate my end users. I would prefer to see django-tailwind parse the template after the template variables have been rendered.

mgax commented 2 years ago

Does this basically mean that Tailwind is parsing the template before it's been rendered, as it ends up seeing the template variable syntax, ie {{product.color}} and ignores it since it's not a valid value?

Yep! Tailwind just looks at the template file on disk, it knows nothing about Django and its template system.

You might have some luck using CSS variables which you can then override in the Django template.

Jonas-SRB commented 1 year ago

I had a similar issue -- one workaround outside of tailwind is to just set a plain vanilla style on the related object: <div style="background-color: {{ company.color_two }}>...</div>"