skip to Main Content

I’m with Tailwind in a Laravel App. While using some TW classes with dynamic params in any Blade view as:

<div class="bg-[url('{{ $myBackgroundImageWithPublicSubPath }}')]" > Any content </div>

it does not works when rendering the page in the browser. Inspecting the source seems like that class was missing.

As TW docs clearly said (https://tailwindcss.com/docs/content-configuration#dynamic-class-names) TW struggle with dynamic classes because they are using regular expressions inspecting the source code in order to prune the final css bundle, then it miss the proper class as not find it in the view’s script.

Do you found any walk around to this problem?

2

Answers


  1. Chosen as BEST ANSWER

    Finally I found a very rude but effective method to solve this.

    Simply add a comment with a plain class (without vars) into the view's html as:

    <-- bg-[url('')] -->

    Then TW bundle the function and all will work fine. You can place the comment anywhere in the view included in the php sections so this will do the trick:

    @php
      // TW hack: bg-[url('')], ... (any other needed dynamic class)
    @endphp
    

    I choose this approach because it hide the hack in the final html, and can place it at the start of the view to be aware about it in the future.

    Also you can create a dedicated and not used view to allocate all needed hack but I dismissed because you will miss the track and sense of the needed hacks and also the class will be bundled at anytime for every view needed or not.

    Please, constructive critics & another proposals for this walk around will be welcome.


  2. you’re correct that Tailwind CSS relies on static analysis of your code to generate its styles, and dynamic classes like the one you’re trying to use won’t be included in the final CSS output.

    One workaround is to use inline styles in this case. Laravel allows you to echo variables directly into your Blade templates, so you could do something like this:

    
    <div style="background-image: url('{{ asset($myBackgroundImageWithPublicSubPath) }}');" class="bg-cover">
        Any content
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search