0

I have a laravel installation and have tailwind set to media for dark mode so it uses the systems preference.

How can I now determine if I'm using dark mode from a blade file? In particular I have 2 svg's one I want to use with dark mode and the other with light mode:

@if( [unknown logic] )
    [dark svg]
@else
    [light svg]
@endif

Also I might decide to use class instead of media in the tailwind config as I had implemented a toggle to switch modes. I set a $theme variable for this in my AppServiceProvider.php files boot function:

        view()->composer('layouts.app', function ($view) {
            $theme = \Cookie::get('theme');
            if ($theme != 'dark' && $theme != 'light') {
                $theme = 'light';
            }

            $view->with('theme', $theme);
        });

While this works for the most part it doesn't work until I'm logged in.

So how do I address this so I can switch the theme anywhere in my app using either media or class in my tailwind config?

I have tried to use the $theme value and also tried to get the cookie but i always get the light mode svg

kometen
  • 6,536
  • 6
  • 41
  • 51
ThurstonLevi
  • 664
  • 13
  • 34
  • Why not print both SVGs and display the correct one using CSS? Usually, the server can't determine whether you are using dark or light mode – Nico Haase Mar 23 '23 at 10:52
  • Not really sure how I'd do that? I know I can use dark: prefix but not sure. Are you suggesting adding the svg in a css class say .logo and then using class="logo dark:logo {etc}" in the blade file? This would be two files with the svg in them right? – ThurstonLevi Mar 23 '23 at 11:02
  • "This would be two files with the svg in them right?" - no, two divs, one to be shown, one to be hidden – Nico Haase Mar 23 '23 at 11:04

1 Answers1

3

You can use the media query of the tailwind to conditionally show which SVG you want to show, you can apply the classes directly into the SVG element if you wish as I have done it in the parent div.

<div class="hidden dark:flex">
    My SVG if theme is dark
</div>
<div class="flex dark:hidden">
    My SVG if theme is light
</div>

The server for the most part does not know about your theme. So let the browser (HTML, CSS, JS) handle the conditional rendering according to the theme and not PHP. But if you really want to send only one SVG element, see this question to get your preferred theme How do I detect dark mode using JavaScript?, and save it in a cookie or your database.

Hope this helps. Thank you.

Sanskar
  • 91
  • 6