Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte: Specify multiple conditional class attributes

I would like to have something like this made possible:

<div 
   class="overflow-scroll h-screen antialiased ..."
   class:whiteTheme="bg-gray-100 text-gray-800 ..."
   class:darkTheme="bg-blue-900 ..."
>
...
</div>

So one set of classes that will always be applied. One set only if whiteTheme is true and another only if darkTheme is true.

I know that i can define a whiteTheme and a darkTheme css class and make it just work like that

<div 
   class="overflow-scroll h-screen antialiased ..."
   class:whiteTheme
   class:darkTheme
>

But the point is that i want to design each element individual (esp. in the starting phase of my application). And having to define my set of classes for each element in a different class... defies for me the purpose in using Tailwind.css and experimenting on the specific elements (without jumping back and forth between css definitions and element definitions).

Another way i could choose is this:

<div 
   class="overflow-scroll h-screen antialiased ... {whiteTheme?'bg-gray-100 text-gray-800 ...':'bg-blue-900 ...'}">

This is kind of ok, but i would love to increase readability and maintainability by defining things in separate attributes...

So i'm wondering if there is a way to make it work the way i want to... E.g. can i extend the Svelte compiler for that easily ?

best Johannes

like image 329
oae Avatar asked Jan 28 '20 02:01

oae


1 Answers

You are close with one of your proposals, but it does the opposite of what you want: class:something={condition}

This will apply the something class when the condition is met.

So in your case you would have to do

class:bg-gray-100={whiteTheme}
class:text-gray-800={whiteTheme}

As an alternative you could do

<script>
 $: whiteThemeClasses = whiteTheme ? "gray text..." : "";
 ...
...class=" fixedclasses {whiteThemeClasses} {blackThemeClasses}
like image 110
Stephane Vanraes Avatar answered Sep 28 '22 01:09

Stephane Vanraes